How to fix apps containing an unsafe implementation of TrustManager and HostnameVerifier - android-security

After upload my apps in Google play Store, getting a mail from google that the app are using an unsafe implementation of the TrustManager and HostnameVerifier. How to fix this problem? Can someone give me a direction?
public class HttpsTrustManager implements X509TrustManager {
private static TrustManager[] trustManagers;
private static final X509Certificate[] _AcceptedIssuers = new X509Certificate[]{};
#Override
public void checkClientTrusted(
java.security.cert.X509Certificate[] x509Certificates, String s)
throws java.security.cert.CertificateException {
}
#Override
public void checkServerTrusted(
java.security.cert.X509Certificate[] x509Certificates, String s)
throws java.security.cert.CertificateException {
}
public boolean isClientTrusted(X509Certificate[] chain) {
return true;
}
public boolean isServerTrusted(X509Certificate[] chain) {
return true;
}
#Override
public X509Certificate[] getAcceptedIssuers() {
return _AcceptedIssuers;
}
public static void allowAllSSL() {
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
#Override
public boolean verify(String arg0, SSLSession arg1) {
return true;
}
});
SSLContext context = null;
if (trustManagers == null) {
trustManagers = new TrustManager[]{new HttpsTrustManager()};
}
try {
context = SSLContext.getInstance("TLS");
context.init(null, trustManagers, new SecureRandom());
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
HttpsURLConnection.setDefaultSSLSocketFactory(context
.getSocketFactory());
}
}
I have tried the above code.

Related

Save data from fragment to custom session

I am creating a project in which I am using navigation drawer and on navigation item click it opens a login page and after login it movies to my main activity. Now, I want to save my login details and all data in my custom shared preference from the fragment. After that it on app restarts and I go to navigation login items it should check if the user is already logged in then it should move to an activity otherwise it should run my login fragment
my login fragment
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
CDSMainViewModel =
ViewModelProviders.of(this).get(CDP_MainViewModel.class);
View root = inflater.inflate(R.layout.fragment_cdplogin, container, false);
context = container.getContext();
context = getActivity().getApplicationContext();
session = new Session(context);
if (session.isLoggedIn()) {
Intent itra = new Intent(getActivity().getApplicationContext(), Verification_Activity.class);
startActivity(itra);
getActivity().finish();
}
else{
login_button = root.findViewById(R.id.button_click_login);
edit1 = root.findViewById(R.id.input_username);
edit2 = root.findViewById(R.id.input_password);
layout_1 = root.findViewById(R.id.usnamelayout);
layout_2 = root.findViewById(R.id.password_layout);
login_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
return root;
}
private void Login_data() {
String URL = "http://117.240.196.238:8080/api/cdp/getAuth";
Log.i("response", URL);
StringRequest jsonObjRequest = new StringRequest(
Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("response_login", response);
parseData1(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("volley", "Error: " + error.getMessage());
showServerConnectionError();
}
}) {
#Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded; charset=UTF-8";
}
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("AuthID", name);
params.put("AuthPwd", password);
return params;
}
};
RequestQueue queue = SingletonRequestQueue.getInstance(getActivity().getApplicationContext()).getRequestQueue();
queue.add(jsonObjRequest);
}
private void parseData1(String response){
try {
JSONObject json = new JSONObject(response);
int success = json.getInt("success");
String msg = json.getString("message");
if(success == 1){
Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
JSONArray recData = json.getJSONArray("data");
for (int i = 0; i < recData.length(); i++) {
JSONObject c = recData.getJSONObject(i);
String uname = name;
String upass = password;
String emp_id = c.getString("emp_id");
String empname = c.getString("EmpName");
String office = c.getString("OfficeNameFull");
String desig = c.getString("DesignationName");
String mobile = c.getString("EmpMobile");
String office_code = c.getString("OfficeCode");
String OfficeType = c.getString("OfficeType");
String district = c.getString("DistrictCode");
String DistrictName = c.getString("DistrictName");
String designationCode = c.getString("designationCode");
String DesignationName1 = c.getString("DesignationName1");
String DesigShortName = c.getString("DesigShortName");
Log.i("session",district);
//Here my loginsession is not working its not saving my data in my session..
Session.getInstance(getContext()).loginsession(emp_id,uname,upass,empname,office,desig,mobile,office_code,OfficeType,district,DistrictName,designationCode,DesignationName1,DesigShortName);
// String email = SessionManager.getInstance(context).getUserEmail();
// session.loginsession(emp_id,uname,upass,empname,office,desig,mobile,office_code,OfficeType,district,DistrictName,designationCode,DesignationName1,DesigShortName);
Intent its12 = new Intent(getActivity().getApplicationContext(), Verification_Activity.class);
startActivity(its12);
getActivity().overridePendingTransition(R.anim.from_right, R.anim.slide_to_left);
getActivity().finish();
}
} else {
Toast.makeText(context,msg, Toast.LENGTH_LONG).show();
}
}catch(Exception ex){
}
}
}
//Session manager class
package com.example.agridept.domain;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import com.example.agridept.ui.CDP_login.CDP_MainFragment;
public class Session {
private static Session jInstance;
SharedPreferences preferences;
SharedPreferences.Editor editor;
Context context;
int PRIVATE_MODE = 0;
private static final String IS_LOGIN = "IsLoggedIn";
private static final String PREF_NAME = "AndroidHivePref";
String emp_id1,username1,password1 ,empname1 , office1 , desig1, mobile1, office_code1, OfficeType1 , district1 ,DistrictName1 , designationCode1, DesignationName11 , DesigShortName1;
public Session(Context context){
this.context = context;
preferences = context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = preferences.edit();
}
public void loginsession(String emp_id,String username,String password11 ,String empname ,String office ,String desig,String mobile,String office_code,String OfficeType ,String district ,String DistrictName ,String designationCode,String DesignationName1 ,String DesigShortName){
editor.putBoolean(IS_LOGIN, true);
editor.putString(emp_id1,emp_id);
editor.putString(username1,username);
editor.putString(password1,password11);
editor.putString(empname1,empname);
editor.putString(office1,office);
editor.putString(desig1,desig);
editor.putString(mobile1,mobile);
editor.putString(office_code1,office_code);
editor.putString(OfficeType1,OfficeType);
editor.putString(district1,district);
editor.putString(DistrictName1,DistrictName);
editor.putString(designationCode1,designationCode);
editor.putString(DesignationName11,DesignationName1);
editor.putString(DesigShortName1,DesigShortName);
}
public boolean isLoggedIn() {
return preferences.getBoolean(IS_LOGIN, false);
}
public void logoutUser() {
// Clearing all data from Shared Preferences
editor.clear();
editor.commit();
// After logout redirect user to Loing Activity
Intent i = new Intent(context, CDP_MainFragment.class);
// Closing all the Activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Add new Flag to start new Activity
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Staring Login Activity
context.startActivity(i);
}
public void clearinfo() {
// Clearing all data from Shared Preferences
editor.clear();
editor.commit();
}
public SharedPreferences getPreferences() {
return preferences;
}
public void setPreferences(SharedPreferences preferences) {
this.preferences = preferences;
}
public SharedPreferences.Editor getEditor() {
return editor;
}
public void setEditor(SharedPreferences.Editor editor) {
this.editor = editor;
}
public Context getContext() {
return context;
}
public void setContext(Context context) {
this.context = context;
}
public int getPRIVATE_MODE() {
return PRIVATE_MODE;
}
public void setPRIVATE_MODE(int PRIVATE_MODE) {
this.PRIVATE_MODE = PRIVATE_MODE;
}
public static String getIsLogin() {
return IS_LOGIN;
}
public static String getPrefName() {
return PREF_NAME;
}
public String getEmp_id1() {
return emp_id1;
}
public void setEmp_id1(String emp_id1) {
this.emp_id1 = emp_id1;
}
public String getPassword1() {
return password1;
}
public void setPassword1(String password1) {
this.password1 = password1;
}
public String getEmpname1() {
return empname1;
}
public void setEmpname1(String empname1) {
this.empname1 = empname1;
}
public String getOffice1() {
return office1;
}
public void setOffice1(String office1) {
this.office1 = office1;
}
public String getDesig1() {
return desig1;
}
public void setDesig1(String desig1) {
this.desig1 = desig1;
}
public String getMobile1() {
return mobile1;
}
public void setMobile1(String mobile1) {
this.mobile1 = mobile1;
}
public String getOffice_code1() {
return office_code1;
}
public void setOffice_code1(String office_code1) {
this.office_code1 = office_code1;
}
public String getOfficeType1() {
return OfficeType1;
}
public void setOfficeType1(String officeType1) {
OfficeType1 = officeType1;
}
public String getDistrict1() {
return district1;
}
public void setDistrict1(String district1) {
this.district1 = district1;
}
public String getDistrictName1() {
return DistrictName1;
}
public void setDistrictName1(String districtName1) {
DistrictName1 = districtName1;
}
public String getDesignationCode1() {
return designationCode1;
}
public void setDesignationCode1(String designationCode1) {
this.designationCode1 = designationCode1;
}
public String getDesignationName11() {
return DesignationName11;
}
public void setDesignationName11(String designationName11) {
DesignationName11 = designationName11;
}
public String getDesigShortName1() {
return DesigShortName1;
}
public void setDesigShortName1(String desigShortName1) {
DesigShortName1 = desigShortName1;
}
public static synchronized Session getInstance(Context context) {
if (jInstance != null) {
return jInstance;
} else {
jInstance = new Session(context);
return jInstance;
}
}
}

JavaFx: How to replace a comma to a dot in TextfieldTableCell

What im doing wrong here?
i tried to use function replace() on my setOnEditCommit, but not work.
clnVt.setCellValueFactory(new PropertyValueFactory<>("valorVt"));
clnVt.setEditable(true);
clnVt.setCellFactory(TextFieldTableCell.forTableColumn(new DoubleStringConverter()));
clnVt.setOnEditCommit(new EventHandler<CellEditEvent<GSTabela2, Double>>() {
#Override
public void handle(CellEditEvent<GSTabela2, Double> c) {
Double valor = c.getTableView().getItems().get(c.getTablePosition().getRow()).valorVtProperty().getValue();
String converte = valor.toString().replace(",", ".");
c.getTableView().getItems().get(c.getTablePosition().getRow()).setValorVt(Double.valueOf(converte));
}
});
Then i try to use a DoubleStringConverter implemention:
public class EstilizadoDoubleStringConverter extends DoubleStringConverter {
private final DoubleStringConverter conversor = new DoubleStringConverter();
#Override
public Double fromString(String value) {
try {
value.replace(",", ".");
return conversor.fromString(value);
} catch (NumberFormatException e) {
e.getStackTrace();
}
return -1.0;
}
#Override
public String toString(Double value) {
try {
return conversor.toString(value);
} catch (NumberFormatException e) {
e.getStackTrace();
}
return null;
}
}
If i use a the DoubleStringConverter a get -1.0;
So, my question is. How i can replace the comma to dot?
I fix with Slaw Hint.
In my implemention of DoubleStringConverter, i change the
private final DoubleStringConverter conversor = new DoubleStringConverter();
to
private final Locale local = Locale.getDefault(Category.FORMAT);
private final NumberStringConverter conversor = new NumberStringConverter(local);
so my whole implemention its now like this.
public class EstilizadoDoubleStringConverter extends DoubleStringConverter {
private final Locale local = Locale.getDefault(Category.FORMAT);
private final NumberStringConverter conversor = new NumberStringConverter(local);
#Override
public Double fromString(String value) {
try {
return conversor.fromString(value).doubleValue();
} catch (NumberFormatException e) {
e.getStackTrace();
}
return -1.0;
}
#Override
public String toString(Double value) {
try {
return conversor.toString(value);
} catch (NumberFormatException e) {
e.getStackTrace();
}
return null;
}
}

Onion Architecture Unit Of Work Transaction Not getting Connection String

I am using Onion Architecture with Autofac. In my Dependency Injection Code, I am using:
[assembly: WebActivatorEx.PostApplicationStartMethod(typeof(IocConfig), "RegisterDependencies")]
namespace AppMVC.Infrastructure.Bootstrapper
{
public class IocConfig
{
public static void RegisterDependencies()
{
var builder = new ContainerBuilder();
builder.RegisterType(typeof(UnitOfWork)).As(typeof(IUnitOfWork)).InstancePerHttpRequest();
builder.Register<IEntitiesContext>(b =>
{
var context = new MyContext("My Connection String");
return context;
}).InstancePerHttpRequest();
}
}
}
Unit Of Work Code:
public class UnitOfWork : IUnitOfWork
{
private readonly IEntitiesContext _context;
private bool _disposed;
private Hashtable _repositories;
public UnitOfWork(IEntitiesContext context)
{
_context = context;
}
public int SaveChanges()
{
return _context.SaveChanges();
}
public IRepository<TEntity> Repository<TEntity>() where TEntity : BaseEntity
{
if (_repositories == null)
{
_repositories = new Hashtable();
}
var type = typeof(TEntity).Name;
if (_repositories.ContainsKey(type))
{
return (IRepository<TEntity>)_repositories[type];
}
var repositoryType = typeof(EntityRepository<>);
_repositories.Add(type, Activator.CreateInstance(repositoryType.MakeGenericType(typeof(TEntity)), _context));
return (IRepository<TEntity>)_repositories[type];
}
public void BeginTransaction()
{
_context.BeginTransaction();
}
public int Commit()
{
return _context.Commit();
}
public void Rollback()
{
_context.Rollback();
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
public virtual void Dispose(bool disposing)
{
if (!_disposed && disposing)
{
_context.Dispose();
foreach (IDisposable repository in _repositories.Values)
{
repository.Dispose();// dispose all repositries
}
}
_disposed = true;
}
}
MyContext Code:
public class MyContext : DbContext, IEntitiesContext
{
private ObjectContext _objectContext;
private DbTransaction _transaction;
public MyContext(string nameOrConnectionString)
: base(nameOrConnectionString)
{
}
public void BeginTransaction()
{
_objectContext = ((IObjectContextAdapter)this).ObjectContext;
if (_objectContext.Connection.State == ConnectionState.Open)
{
if (_transaction == null)
{
_transaction = _objectContext.Connection.BeginTransaction();
}
return;
}
_objectContext.Connection.Open(); // At this Line, I am getting Exception
if (_transaction == null)
{
_transaction = _objectContext.Connection.BeginTransaction();
}
}
public int Commit()
{
var saveChanges = SaveChanges();
_transaction.Commit();
return saveChanges;
}
public void Rollback()
{
_transaction.Rollback();
}
}
My problem is, On _objectContext.Connection.Open();, I am getting Connection String missing error.
Below is the screenshot of the Exception:

Multiple Query Params with Asyncronous Call Retrofit

UPDATE:
I have learned what I am looking to do is to use the Async within Retrofit with multiple queries too. I have updated my code, but I cannot get the async with the queries.
I am using Retrofit to make my data calls to a movie database and need to change the sort order depending on user settings. I am not clear how I could add this functionality to my interface.
sort_by=highest_rating.desc
or
sort_by=popularity.desc
Interface:
public interface MovieDatabaseApiCient {
#GET("/3/discover/movie")
void getData(#Query("api_key") String apiKey, #Query("sort_by") String sortByValue, Callback<MovieDbModel> response);
}
UPDATED API INTERFACE:
public interface MovieDatabaseApiCient {
#GET("/3/discover/movie?sort_by=popularity.desc&api_key=xxxxxxx")
void getMoviesByPopularityDesc(Callback<MovieDbModel> response);
#GET("/3/discover/movie?sort_by=vote_average_desc&api_key=xxxxxxxx")
void getMoviesByVotingDesc(Callback<MovieDbModel> response);
}
UPDATED DATA CALL THAT WORKS:
private void makeDataCall(String sortPreference) {
final RestAdapter restadapter = new RestAdapter.Builder().setEndpoint(ENDPOINT_URL).build();
MovieDatabaseApiCient apiLocation = restadapter.create(MovieDatabaseApiCient.class);
if (sortPreference.equals(this.getString(R.string.sort_order_popularity)) ){
apiLocation.getMoviesByPopularityDesc (new Callback<MovieDbModel>() {
#Override
public void success(MovieDbModel movieModels, Response response) {
movieDbResultsList = movieModels.getResults();
MoviesGridViewAdapter adapter = new MoviesGridViewAdapter(getApplicationContext(), R.layout.movie_gridview_item, movieDbResultsList);
gridView.setAdapter(adapter);
}
#Override
public void failure(RetrofitError error) {
Log.d("ERROR", error.toString());
Toast.makeText(getApplicationContext(), "Error: " + error.toString(), Toast.LENGTH_SHORT).show();
}
});
} else {
apiLocation.getMoviesByVotingDesc( new Callback<MovieDbModel>() {
#Override
public void success(MovieDbModel movieModels, Response response) {
movieDbResultsList = movieModels.getResults();
MoviesGridViewAdapter adapter = new MoviesGridViewAdapter(getApplicationContext(), R.layout.movie_gridview_item, movieDbResultsList);
gridView.setAdapter(adapter);
}
#Override
public void failure(RetrofitError error) {
Log.d("ERROR", error.toString());
Toast.makeText(getApplicationContext(), "Error: " + error.toString(), Toast.LENGTH_SHORT).show();
}
});
}
}
My call for the data:
private void makeDataCall (String apiKey, String sortPreference) {
final RestAdapter restadapter = new RestAdapter.Builder().setEndpoint(ENDPOINT_URL).build();
MovieDatabaseApiCient apiLocation = restadapter.create(MovieDatabaseApiCient.class);
apiLocation.getData(apiKey, sortPreference, new Callback<MovieDbModel>){
#Override
public void success(MovieDbModel movieModels, Response response) {
movieDbResultsList = movieModels.getResults();
MoviesGridViewAdapter adapter = new MoviesGridViewAdapter(getApplicationContext(), R.layout.movie_gridview_item, movieDbResultsList);
gridView.setAdapter(adapter);
}
#Override
public void failure(RetrofitError error) {
Log.d("ERROR", error.toString());
Toast.makeText(getApplicationContext(), "Error: " + error.toString(), Toast.LENGTH_SHORT).show();
}
});
}
I found a way to do Synchronously, but not asynchronously.
From your question and comment, IHMO, you should import retrofit.Callback; instead of import com.squareup.okhttp.Callback;
My code as the following has no compile error:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// creating a RestAdapter using the custom client
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint(API_URL_BASE)
.setLogLevel(RestAdapter.LogLevel.FULL)
.setClient(new OkClient(mOkHttpClient))
.build();
WebService webService = restAdapter.create(WebService.class);
retrofit.Callback<GetRoleData> callback = new Callback<GetRoleData>() {
#Override
public void success(GetRoleData getRoleData, retrofit.client.Response response) {
}
#Override
public void failure(RetrofitError error) {
}
};
webService.getData("api_key", "sort_by", callback);
}
Interface:
public interface WebService {
#GET("/3/discover/movie")
void getData(#Query("api_key") String apiKey, #Query("sort_by") String sortByValue, Callback<GetRoleData> response);
}
So, please check your code again

Retrofit Observables and access to Response

I'm using Retrofit and RxJava but can't seem to do what I want.
Here's my declaration of my web service:
Observable<Response> rawRemoteDownload(#Header("Cookie") String token, #Path("programId") int programId);
The problem I have is the webservice is returning a 403 and a json payload with details.
Retrofit calls onError, only passing the Throwable so I can't check the response body.
Here's part of my test code
apiManager.rawRemoteDownloadRequest("token", 1).subscribe(new Observer<Response>() {
#Override
public void onCompleted() {
}
#Override
public void onError(Throwable e) {
// this is called and I've lost the response!
}
#Override
public void onNext(Response response) {
}
});
SOLUTION:
Thanks to Gomino, I went with this as a solution:
new Action1<Throwable>() {
#Override
public void call(Throwable throwable) {
if (throwable instanceof RetrofitError) {
Response response = ((RetrofitError) throwable).getResponse();
System.out.println(convertToString(response.getBody()));
}
}
where convertToString looks like:
private String convertToString(TypedInput body) {
byte[] bodyBytes = ((TypedByteArray) body).getBytes();
return new String(bodyBytes);
}
Check if the throwable is a RetrofitError:
#Override
public void onError(Throwable e) {
if (e instanceof RetrofitError) {
Response response = ((RetrofitError) e).getResponse();
}
}

Resources