In the map view the zoom in and out, location pointer which I have added in my program is visible but the map is not visible.
Please help me to figure out what the error is.
This is my main activity file:
package com.example.lenovo.googlemaps;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback,
GoogleMap.OnMyLocationChangeListener,
android.location.LocationListener {
private GoogleMap mGoogleMap;
private Geocoder mGeocoder;
private GoogleApiClient mGoogleApiClient = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
SupportMapFragment mSupportMapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mSupportMapFragment.getMapAsync(this);
mGeocoder = new Geocoder(this, Locale.getDefault());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main1, menu);
return true;
}
#Override
protected void onPause() {
super.onPause();
stopLocationUpdates();
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
}
protected void stopLocationUpdates() {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, (LocationListener) this);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.normal:
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
break;
case R.id.satellite:
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
break;
case R.id.terrain:
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
break;
case R.id.hybrid:
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
break;
case R.id.none:
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_NONE);
break;
}
return true;
}
#Override
public void onMapReady(GoogleMap googleMap) {
mGoogleMap = googleMap;
mGoogleMap.getUiSettings().setZoomControlsEnabled(true);
mGoogleMap.getUiSettings().setCompassEnabled(true);
mGoogleMap.getUiSettings().setMyLocationButtonEnabled(true);
mGoogleMap.setMyLocationEnabled(true);
mGoogleMap.setOnMyLocationChangeListener(this);
showMyLocationOnScreen();
}
#Override
public void onMyLocationChange(Location location) {
showMyLocationOnScreen();
}
private void showMyLocationOnScreen() {
double lat = 28.666667;
double lon = 71.216667;
Toast.makeText(this, lat + "\n" + lon, Toast.LENGTH_LONG).show();
LatLng latLng = new LatLng(lat, lon);
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 13));
mGoogleMap.addMarker(new MarkerOptions()
.title("India")
.snippet("The capital city")
.position(latLng));
try {
List<Address> addresses = mGeocoder.getFromLocation(lat, lon, 5);
if (addresses != null && addresses.size() > 0) {
for (Address address : addresses) {
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < address.getMaxAddressLineIndex(); i++) {
stringBuilder.append(address.getAddressLine(i));
stringBuilder.append("\n");
}
Log.i("edureka", stringBuilder.toString());
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
}
This is my manifest File:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.lenovo.googlemaps">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.MAPS_RECIEVE"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-feature android:glEsVersion="0x00020000" android:required="true"/>
<uses-library android:name="com.google.android.maps"/>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<!--
The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
Google Maps Android API v2, but are recommended.
-->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-feature android:glEsVersion="0x00020000"
android:required="true"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MapsActivity"
android:label="GoogleMaps" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="AIzaSyCN6pHntLjsD6PGmu9UMkWNyY3O8071oIo"/>
</application>
</manifest>
Related
I am trying to get JSONObject from the Pokeapi in my Pokedex app, but it seems that there is no response and the volley error is produced. However, the link opens perfectly fine in my browser showing the JSON. I tried different links to the JSON, still it does not work. Permission to use internet is added to AndroidManifest. Request is added to RequestQueue. Where could be the problem?
Here is my PokedexAdapter class:
package com.example.pokedex;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class PokedexAdapter extends RecyclerView.Adapter<PokedexAdapter.PokedexViewHolder> {
public static class PokedexViewHolder extends RecyclerView.ViewHolder {
public LinearLayout containerView;
public TextView textView;
PokedexViewHolder(View view) {
super(view);
containerView = view.findViewById(R.id.pokedex_row);
textView = view.findViewById(R.id.pokedex_row_text_view);
containerView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Pokemon current = (Pokemon) containerView.getTag();
Intent intent = new Intent(v.getContext(), PokemonActivity.class);
intent.putExtra("name", current.getName());
//intent.putExtra("number", current.getNumber());
v.getContext().startActivity(intent);
}
});
}
}
private List<Pokemon> pokemon = new ArrayList<>();
private RequestQueue requestQueue;
public PokedexAdapter(Context context) {
requestQueue = Volley.newRequestQueue(context);
loadPokemon();
}
public void loadPokemon() {
String url = "https://pokeapi.co/api/v2/pokemon?limit=151";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray results = response.getJSONArray("results");
for (int i = 0; i < results.length(); i++) {
JSONObject result = results.getJSONObject(i);
pokemon.add(new Pokemon(
result.getString("name"),
result.getString("url")));
}
notifyDataSetChanged();
} catch (JSONException e) {
Log.e("cs50", "onResponse: ", e);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("cs50", "onErrorResponse: pokemon list error");
}
});
requestQueue.add(request);
}
#NonNull
#Override
public PokedexViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.pokedex_row, parent, false);
return new PokedexViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull PokedexViewHolder holder, int position) {
Pokemon current = pokemon.get(position);
holder.textView.setText(current.getName());
holder.containerView.setTag(current);
}
#Override
public int getItemCount() {
return pokemon.size();
}
}
AndroidManifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.pokedex">
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".PokemonActivity"></activity>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Result - nothing is shown on the screen and this error is produced:
2020-06-09 19:09:37.469 15137-15137/com.example.pokedex D/cs50: onErrorResponse: pokemon list error
The problem was solved by reinstalling the app.
This thread was helpful:
java.net.SocketException: socket failed: EPERM (Operation not permitted)
im trying to acsess an application button on javafx program by extenal 'Aspect' class using the spring aop .
This is the aspect class:
public class AspectControl {
private List<String> UserClicks;
private String[] expectedClick={"yellow","greean","red","blue","blue","blue","grean"};
public void beforeClickYellow(){
UserClicks.add("yellow");
}
public void afterClickYellow(){
Thread t=new Thread();
Main.yellowBtn.disableProperty();
}
}
this is the configuration xml :
<?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop = "http://www.springframework.org/schema/aop"
xsi:schemaLocation = "http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">
<aop:aspectj-autoproxy/>
<aop:config>
<aop:aspect id ="aspectcontrol" ref = "control">
<aop:pointcut id ="YellowPointcut"
expression = "execution(*
application.ButtonsNotify.yellowNotify(..))"/>
<aop:before pointcut-ref ="YellowPointcut" method="beforeClickYellow"/>
<aop:after pointcut-ref ="YellowPointcut" method ="afterClickYellow"/>
</aop:aspect>
application class:
package application;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
import javafx.scene.paint.Color;
import javafx.scene.paint.CycleMethod;
import javafx.scene.paint.LinearGradient;
import javafx.scene.paint.Stop;
import javafx.scene.shape.Ellipse;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.transform.Rotate;
import javafx.scene.transform.Translate;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import javafx.stage.WindowEvent;
public class Main extends Application {
private static final int SCENE_WIDTH = 800;
private static final int SCENE_HEIGHT = 500;
private Group GroupButtns;
private final int TOTAL_CLICKS = 10;
private int numOfClick = 0;
public static Button yellowBtn;
#Override
public void start(final Stage stage) {
stage.initStyle(StageStyle.TRANSPARENT);
stage.sizeToScene();
stage.setScene(new AppScene());
//close application
final Button close = new Button("X");
close.setFont(Font.font("Arial", FontWeight.BOLD, 20));
close.setStyle("-fx-background-color:transparent;-fx-text-fill:red;");
close.setOpacity(0);
close.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent arg0) {
Platform.exit();
System.exit(0);
}
});
close.setTranslateY(stage.getScene().getHeight() - 20);
stage.getScene().setOnMouseEntered(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent arg0) {
close.setOpacity(1);
}
});
stage.getScene().setOnMouseExited(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent arg0) {
close.setOpacity(0);
}
});
// close application
stage.setOnCloseRequest(new EventHandler<WindowEvent>() {
#Override
public void handle(WindowEvent t) {
Platform.exit();
System.exit(0);
}
});
yellowBtn = new Button();
SetButnView(yellowBtn, "yellow");
yellowBtn.setTranslateY(stage.getScene().getHeight() - 250);
yellowBtn.setTranslateX(stage.getScene().getX() - 200);
yellowBtn.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent arg0) {
numOfClick += 1;
ApplicationContext context = new ClassPathXmlApplicationContext("BeanConfig.xml");
ButtonsNotify notify = (ButtonsNotify) context.getBean("btnNotify");
notify.yellowNotify(numOfClick);
}
});
Button blueBtn = new Button();
SetButnView(blueBtn, "blue");
blueBtn.setTranslateY(stage.getScene().getHeight() - 250);
blueBtn.setTranslateX(stage.getScene().getX() - 10);
Button redbtn = new Button();
SetButnView(redbtn, "red");
redbtn.setTranslateY(stage.getScene().getHeight() - 420);
redbtn.setTranslateX(stage.getScene().getX() - 10);
Button greenbtn = new Button();
SetButnView(greenbtn, "green");
greenbtn.setTranslateY(stage.getScene().getHeight() - 420);
greenbtn.setTranslateX(stage.getScene().getX() - 200);
GroupButtns.getChildren().add(close);
GroupButtns.getChildren().add(yellowBtn);
GroupButtns.getChildren().add(blueBtn);
GroupButtns.getChildren().add(greenbtn);
GroupButtns.getChildren().add(redbtn);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
private class AppScene extends Scene {
public AppScene() {
super(GroupButtns = new Group(), SCENE_WIDTH, SCENE_HEIGHT, Color.TRANSPARENT);
GroupButtns.setClip(new Ellipse(0, SCENE_HEIGHT / 2, SCENE_WIDTH / 3, SCENE_HEIGHT / 2)); //Scene shape and size
Rectangle background = new Rectangle(-SCENE_WIDTH / 2, 0, SCENE_WIDTH, SCENE_HEIGHT);
background.setFill(new LinearGradient(0, 0, 0, SCENE_HEIGHT, false, CycleMethod.NO_CYCLE, new Stop(0, Color.GRAY), new Stop(0.3, Color.GRAY),
new Stop(1., new Color(1, 1, 1, 0)))); //background color
GroupButtns.getChildren().add(background);
GroupButtns.getTransforms().addAll(new Translate(SCENE_WIDTH / 2, SCENE_HEIGHT), new Rotate(180));
}
}
public void SetButnView(Button btn, String color) {
if (color.equals("yellow")) {
Image src = new Image(getClass().getResourceAsStream("yellow1.png"));
btn.setGraphic(new ImageView(src));
}
if (color.equals("blue")) {
Image src = new Image(getClass().getResourceAsStream("blue1.png"));
btn.setGraphic(new ImageView(src));
}
if (color.equals("red")) {
Image src = new Image(getClass().getResourceAsStream("red1.png"));
btn.setGraphic(new ImageView(src));
}
if (color.equals("green")) {
Image src = new Image(getClass().getResourceAsStream("green1.png"));
btn.setGraphic(new ImageView(src));
}
}
}
And this is the poincut class which I call every time I press a btn on the application class:
package application;
public class ButtonsNotify {
public ButtonsNotify(){
}
public void yellowNotify(int clickNumber){
System.out.println("yellow");
}
public void RedNotify(int clickNumber){
System.out.println("red");
}
public void BlueNotify(int clickNumber){
System.out.println("blue");
}
public void GreenNotify(int clickNumber){
System.out.println("green");
}
}
How can I control the button's visability by the 'AspectControl' class??
I am using Spring security 4.0. My login module is configured in Application server so I have to do authentication using JAAS but my user details are stored in database, so once authenticated user object will be created by querying database. Could you please let me know how to achieve this i.e. LDAP authentication and load user details from database. Also how cache the user object using eh-cache, so that the user object can be accessed in the service / dao layer.
This can be achieved using CustomAuthentication Provider. Below are the codes.
import java.util.Arrays;
import java.util.List;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.authentication.jaas.JaasGrantedAuthority;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import com.sun.security.auth.UserPrincipal;
public class CustomAutenticationProvider extends DaoAuthenticationProvider implements AuthenticationProvider {
private AuthenticationProvider delegate;
public CustomAutenticationProvider(AuthenticationProvider delegate) {
this.delegate = delegate;
}
#Override
public Authentication authenticate(Authentication authentication) {
Authentication a = delegate.authenticate(authentication);
if(a.isAuthenticated()){
a = super.authenticate(a);
}else{
throw new BadCredentialsException(messages.getMessage(
"AbstractUserDetailsAuthenticationProvider.badCredentials",
"Bad credentials"));
}
return a;
}
private List<GrantedAuthority> loadRolesFromDatabaseHere(String name) {
GrantedAuthority grantedAuthority =new JaasGrantedAuthority(name, new UserPrincipal(name));
return Arrays.asList(grantedAuthority);
}
#Override
public boolean supports(Class<?> authentication) {
return delegate.supports(authentication);
}
/* (non-Javadoc)
* #see org.springframework.security.authentication.dao.DaoAuthenticationProvider#additionalAuthenticationChecks(org.springframework.security.core.userdetails.UserDetails, org.springframework.security.authentication.UsernamePasswordAuthenticationToken)
*/
#Override
protected void additionalAuthenticationChecks(UserDetails userDetails,
UsernamePasswordAuthenticationToken authentication)
throws AuthenticationException {
if(!authentication.isAuthenticated())
throw new BadCredentialsException(messages.getMessage(
"AbstractUserDetailsAuthenticationProvider.badCredentials",
"Bad credentials"));
}
}
UserDetails required for DAOAuthentication
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import com.testjaas.model.User;
import com.testjaas.model.UserRepositoryUserDetails;
#Component
public class AuthUserDetailsService implements UserDetailsService {
#Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
System.out.println("loadUserByUsername called !!");
com.testjaas.model.User user = new User();
user.setName(username);
user.setUserRole("ROLE_ADMINISTRATOR");
if(null == user) {
throw new UsernameNotFoundException("User " + username + " not found.");
}
return new UserRepositoryUserDetails(user);
}
}
RoleGrantor - This will be a dummy class required for Spring JAAS authentication
import java.security.Principal;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.springframework.security.authentication.jaas.AuthorityGranter;
public class RoleGranterFromMap implements AuthorityGranter {
private static Map<String, String> USER_ROLES = new HashMap<String, String>();
static {
USER_ROLES.put("test", "ROLE_ADMINISTRATOR");
//USER_ROLES.put("test", "TRUE");
}
public Set<String> grant(Principal principal) {
return Collections.singleton("DUMMY");
}
}
SampleLogin - This should be replaced with your login module
import java.io.Serializable;
import java.security.Principal;
import java.util.HashMap;
import java.util.Map;
import javax.security.auth.Subject;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.NameCallback;
import javax.security.auth.callback.PasswordCallback;
import javax.security.auth.login.LoginException;
import javax.security.auth.spi.LoginModule;
public class SampleLoginModule implements LoginModule {
private Subject subject;
private String password;
private String username;
private static Map<String, String> USER_PASSWORDS = new HashMap<String, String>();
static {
USER_PASSWORDS.put("test", "test");
}
public boolean abort() throws LoginException {
return true;
}
public boolean commit() throws LoginException {
return true;
}
public void initialize(Subject subject, CallbackHandler callbackHandler,
Map<String, ?> sharedState, Map<String, ?> options) {
this.subject = subject;
try {
NameCallback nameCallback = new NameCallback("prompt");
PasswordCallback passwordCallback = new PasswordCallback("prompt",false);
callbackHandler.handle(new Callback[] { nameCallback,passwordCallback });
this.password = new String(passwordCallback.getPassword());
this.username = nameCallback.getName();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public boolean login() throws LoginException {
if (USER_PASSWORDS.get(username) == null
|| !USER_PASSWORDS.get(username).equals(password)) {
throw new LoginException("username is not equal to password");
}
subject.getPrincipals().add(new CustomPrincipal(username));
return true;
}
public boolean logout() throws LoginException {
return true;
}
private static class CustomPrincipal implements Principal, Serializable {
private final String username;
public CustomPrincipal(String username) {
this.username = username;
}
public String getName() {
return username;
}
}
}
Spring XML configuration
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:security="http://www.springframework.org/schema/security"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-4.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd">
<security:http auto-config="true">
<security:intercept-url pattern="/*" access="isAuthenticated()"/>
</security:http>
<!-- <security:authentication-manager>
<security:authentication-provider ref="jaasAuthProvider" />
</security:authentication-manager> -->
<bean id="userDetailsService" class="com.testjaas.service.AuthUserDetailsService"></bean>
<bean id="testService" class="com.testjaas.service.TestService"/>
<bean id="applicationContextProvider" class="com.testjaas.util.ApplicationContextProvider"></bean>
<security:authentication-manager>
<security:authentication-provider ref="customauthProvider"/>
</security:authentication-manager>
<bean id="customauthProvider" class="com.testjaas.security.CustomAutenticationProvider">
<constructor-arg name="delegate" ref="jaasAuthProvider" />
<property name="userDetailsService" ref="userDetailsService" />
</bean>
<bean id="jaasAuthProvider" class="org.springframework.security.authentication.jaas.JaasAuthenticationProvider">
<property name="loginConfig" value="classpath:pss_jaas.config" />
<property name="authorityGranters">
<list>
<bean class="com.testjaas.security.RoleGranterFromMap" />
</list>
</property>
<property name="loginContextName" value="JASSAuth" />
<property name="callbackHandlers">
<list>
<bean class="org.springframework.security.authentication.jaas.JaasNameCallbackHandler" />
<bean class="org.springframework.security.authentication.jaas.JaasPasswordCallbackHandler" />
</list>
</property>
</bean>
</beans>
Sample jaas config
JASSAuth {
com.testjaas.security.SampleLoginModule required;
};
I'm trying to Inject a DAO into #Service component, but I get this error :
Exception in thread "main" java.lang.NullPointerException at
it.cle.project.service.impl.TestEntityServiceImpl.getListTestEntity(TestEntityServiceImpl.java:24).
Fails to call the DAO which is null despite the annotation #Autowired
Below my code:
context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:c="http://www.springframework.org/schema/c"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/jee
http://www.springframework.org/schema/jee/spring-jee-4.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-4.0.xsd">
<!-- INIZIO IMPOSTAZIONI LEGATE ALLE ANNOTATIONS -->
<tx:annotation-driven/>
<context:property-placeholder location="classpath:hibernate.properties"/>
<context:component-scan base-package="it.cle.project.service.impl" />
<context:component-scan base-package="it.cle.project.dao.hbn" />
<context:component-scan base-package="it.cle.project.dao.hibernate" />
<!-- FINE IMPOSTAZIONI LEGATE ALLE ANNOTATIONS -->
<!-- INIZIO IMPOSTAZIONI LEGATE AD ALTRI FILE DI CONFIGURAZIONE -->
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:hibernate.properties"/>
</bean>
<!-- FINE IMPOSTAZIONI LEGATE AD ALTRI FILE DI CONFIGURAZIONE -->
<!-- INIZIO IMPOSTAZIONI LEGATE ALLA CONNESSIONE -->
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager" p:sessionFactory-ref="sessionFactory" />
<util:properties id="hibernateProperties">
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl_auto}</prop>
</util:properties>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"
p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.url}"
p:username="${jdbc.username}"
p:password="${jdbc.password}" />
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean "
p:dataSource-ref="dataSource" p:packagesToScan="it.cle.project.model"
p:hibernateProperties-ref="hibernateProperties" />
<!-- FINE IMPOSTAZIONI LEGATE ALLA CONNESSIONE -->
App.java
package it.cle.project;
import it.cle.project.model.TestEntity;
import it.cle.project.service.impl.TestEntityServiceImpl;
import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class App
{
public static void main( String[] args )
{
ApplicationContext context = new ClassPathXmlApplicationContext("context.xml");
System.out.println( "Hello World!" );
TestEntity testEntity = new TestEntity();
testEntity.setCampoUno("Campo Uno");
testEntity.setCampoDue("Campo Due");
testEntity.setEmail("email#test.it");
TestEntityServiceImpl testEntityServiceImpl = new TestEntityServiceImpl();
List<TestEntity> testEntitys = testEntityServiceImpl.getListTestEntity();
}
}
DAO Interface
package it.cle.project.dao;
import java.io.Serializable;
import java.util.List;
public interface Dao<T extends Object> {
void create(T t);
T get(Serializable id);
T load(Serializable id);
List<T> getAll();
void update(T t);
void delete(T t);
void deleteById(Serializable id);
void deleteAll();
long count();
boolean exists(Serializable id);
}
TestEntityDAO interface
package it.cle.project.dao;
import it.cle.project.model.TestEntity;
import java.util.List;
public interface TestEntityDao extends Dao<TestEntity> {
List<TestEntity> findByEmail(String email);
}
AbstractHbnDao Abstract class:
package it.cle.project.dao.hibernate;
import it.cle.project.dao.Dao;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.util.Date;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ReflectionUtils;
#Service
public abstract class AbstractHbnDao<T extends Object> implements Dao<T> {
#Autowired
private SessionFactory sessionFactory;
private Class<T> domainClass;
protected Session getSession() {
return sessionFactory.getCurrentSession();
}
#SuppressWarnings("unchecked")
private Class<T> getDomainClass() {
if (domainClass == null) {
ParameterizedType thisType =
(ParameterizedType) getClass().getGenericSuperclass();
this.domainClass =
(Class<T>) thisType.getActualTypeArguments()[0];
}
return domainClass;
}
private String getDomainClassName() {
return getDomainClass().getName();
}
public void create(T t) {
Method method = ReflectionUtils.findMethod(
getDomainClass(), "setDataCreazione",
new Class[] { Date.class });
if (method != null) {
try {
method.invoke(t, new Date());
} catch (Exception e) { /* Ignore */ }
}
getSession().save(t);
}
#SuppressWarnings("unchecked")
public T get(Serializable id) {
return (T) getSession().get(getDomainClass(), id);
}
#SuppressWarnings("unchecked")
public T load(Serializable id) {
return (T) getSession().load(getDomainClass(), id);
}
#SuppressWarnings("unchecked")
public List<T> getAll() {
return getSession()
.createQuery("from " + getDomainClassName())
.list();
}
public void update(T t) { getSession().update(t); }
public void delete(T t) { getSession().delete(t); }
public void deleteById(Serializable id) { delete(load(id)); }
public void deleteAll() {
getSession()
.createQuery("delete " + getDomainClassName())
.executeUpdate();
}
public long count() {
return (Long) getSession()
.createQuery("select count(*) from " + getDomainClassName())
.uniqueResult();
}
public boolean exists(Serializable id) { return (get(id) != null); }
}
HbnTestEntityDao class DAO
package it.cle.project.dao.hbn;
import it.cle.project.dao.TestEntityDao;
import it.cle.project.dao.hibernate.AbstractHbnDao;
import it.cle.project.model.TestEntity;
import java.util.List;
import org.springframework.stereotype.Repository;
#Repository
public class HbnTestEntityDao extends AbstractHbnDao<TestEntity> implements TestEntityDao {
#SuppressWarnings("unchecked")
public List<TestEntity> findByEmail(String email) {
return getSession()
.getNamedQuery("findContactsByEmail")
.setString("email", "%" + email + "%")
.list();
}
}
TestEntityService interface service
package it.cle.project.service;
import it.cle.project.model.TestEntity;
import java.util.List;
public interface TestEntityService {
void createTestEntity(TestEntity testEntity);
List<TestEntity> getListTestEntity();
List<TestEntity> getTestEntityByEmail(String email);
TestEntity getTestEntity(Integer id);
void updateTestEntity(TestEntity testEntity);
void deleteTestEntity(Integer id);
}
TestEntityServiceImpl
package it.cle.project.service.impl;
import it.cle.project.dao.TestEntityDao;
import it.cle.project.model.TestEntity;
import it.cle.project.service.TestEntityService;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
#Service
#Transactional
public class TestEntityServiceImpl implements TestEntityService {
#Autowired
private TestEntityDao testEntityDao;
public void createTestEntity(TestEntity testEntity) {
testEntityDao.create(testEntity);
}
public List<TestEntity> getListTestEntity() {
return testEntityDao.getAll();
}
public List<TestEntity> getTestEntityByEmail(String email) {
return testEntityDao.findByEmail(email);
}
public TestEntity getTestEntity(Integer id) {
return testEntityDao.get(id);
}
public void updateTestEntity(TestEntity testEntity) {
testEntityDao.update(testEntity);
}
public void deleteTestEntity(Integer id) {
testEntityDao.deleteById(id);
}
}
Any ideas?
Thanks.
Your TestServiceImpl should be spring managed bean and should be fetched from Spring application context (by injection or by explicit asking the context). As the component scanning is at work, your TestServiceImpl is already managed with Spring's own supplied name (com...TestServiceImpl becomes testServiceImpl). You can give it your name like
#Service("myTestServiceImpl")
The instead of creating the bean yourself you can query this named bean from application context and use it.
That's some wall of text. I stopped at:
TestEntityServiceImpl testEntityServiceImpl = new TestEntityServiceImpl();
You created an unmanaged bean. Spring has no control over that. Put TestEntityServiceImpl into your spring context.
i have the following spring-security.xml file :-
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.0.xsd">
<http auto-config="true">
<intercept-url pattern="/Freelancer/**" access="ROLE_FREELANCE" />
<intercept-url pattern="/Client/**" access="ROLE_CLIENT" />
<intercept-url pattern="/Agency/**" access="ROLE_AGENCY" />
<intercept-url pattern="/Manager/**" access="ROLE_MANAGER" />
<intercept-url pattern="/User/**" access="ROLE_USER" />
<form-login default-target-url="/${role}" login-page="/login.jsp" />
<logout logout-url="/logout" logout-success-url="/" />
</http>
<authentication-manager>
<authentication-provider>
<jdbc-user-service data-source-ref="dataSource"
users-by-username-query="select user_name,password, enabled from Users where user_name=?"
authorities-by-username-query="select u.user_name, u.role from Users u where u.user_name =?"/>
</authentication-provider>
</authentication-manager>
</beans:beans>
what i want, i want to redirect the user to their workspace, for example if Client login then he will be redirected to the /Client/index.jsp, if Agency login, they will be redirected to the /Agency/index.jsp.
is there any way to access the role before, he will be redirected to their workspace in spring-security.xml file.
<form-login default-target-url="/${role}" login-page="/login.jsp" />
I have the directory structure similer to role.
have any idea.
Write a spring controller which will serve different pages to be shown based on user role. Write Authentication success handler class and write code to decide where to redirect based on roles.
First of all <form-login /> tag need to be changed.
<form-login login-page="/landing" authentication-success-handler-ref="authSuccessHandler" />
<beans:bean id="authSuccessHandler" class="com.package.AuthSuccessHandler" />
Remove default-target-url attribute. Let auth handler decide where to redirect the user.
Auth success handler class will be like :
public class AuthSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
#Override
protected String determineTargetUrl(HttpServletRequest request, HttpServletResponse response) {
// Get the role of logged in user
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String role = auth.getAuthorities().toString();
String targetUrl = "";
if(role.contains("client")) {
targetUrl = "/client/index";
} else if(role.contains("agency")) {
targetUrl = "/agency/index";
}
return targetUrl;
}
}
This is a sample code. Change it as per your requirements.
You can use annotation based solution by using custom success handler like this:
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
#Component
public class CustomSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
#Override
protected void handle(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
throws IOException {
String targetUrl = determineTargetUrl(authentication);
if (response.isCommitted()) {
System.out.println("Can't redirect");
return;
}
redirectStrategy.sendRedirect(request, response, targetUrl);
}
/*
* This method extracts the roles of currently logged-in user and returns
* appropriate URL according to his/her role.
*/
protected String determineTargetUrl(Authentication authentication) {
String url = "";
Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
List<String> roles = new ArrayList<String>();
for (GrantedAuthority a : authorities) {
roles.add(a.getAuthority());
}
if (isDba(roles)) {
url = "/db";
} else if (isAdmin(roles)) {
url = "/admin";
} else if (isUser(roles)) {
url = "/home";
} else {
url = "/accessDenied";
}
return url;
}
private boolean isUser(List<String> roles) {
if (roles.contains("ROLE_USER")) {
return true;
}
return false;
}
private boolean isAdmin(List<String> roles) {
if (roles.contains("ROLE_ADMIN")) {
return true;
}
return false;
}
private boolean isDba(List<String> roles) {
if (roles.contains("ROLE_DBA")) {
return true;
}
return false;
}
public void setRedirectStrategy(RedirectStrategy redirectStrategy) {
this.redirectStrategy = redirectStrategy;
}
protected RedirectStrategy getRedirectStrategy() {
return redirectStrategy;
}
}
And security config as:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
#Configuration
#EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
#Autowired
CustomSuccessHandler customSuccessHandler;
#Autowired
public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("bill").password("abc123").roles("USER");
auth.inMemoryAuthentication().withUser("admin").password("root123").roles("ADMIN");
auth.inMemoryAuthentication().withUser("dba").password("root123").roles("ADMIN","DBA");
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/", "/home").access("hasRole('USER')")
.antMatchers("/admin/**").access("hasRole('ADMIN')")
.antMatchers("/db/**").access("hasRole('ADMIN') and hasRole('DBA')")
.and().formLogin().loginPage("/login").successHandler(customSuccessHandler)
.usernameParameter("ssoId").passwordParameter("password")
.and().csrf()
.and().exceptionHandling().accessDeniedPage("/Access_Denied");
}
}
It is better to check roles with equals in granted authority, contains may fail if multiple role exist with a same part.
Add authentication success handler in form login config like below:
<http auto-config="true">
<intercept-url pattern="/Freelancer/**" access="ROLE_FREELANCE" />
<intercept-url pattern="/Client/**" access="ROLE_CLIENT" />
<intercept-url pattern="/Agency/**" access="ROLE_AGENCY" />
<intercept-url pattern="/Manager/**" access="ROLE_MANAGER" />
<intercept-url pattern="/User/**" access="ROLE_USER" />
<form-login login-page='/login.html'
authentication-failure-url="/login.html?error=true"
authentication-success-handler-ref="myAuthenticationSuccessHandler"/>
<logout logout-url="/logout" logout-success-url="/" />
</http>
And the success handler goes like this:
public class MySimpleUrlAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
protected Log logger = LogFactory.getLog(this.getClass());
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
#Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
handle(request, response, authentication);
clearAuthenticationAttributes(request);
}
protected void handle(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
String targetUrl = determineTargetUrl(authentication);
if (response.isCommitted()) {
logger.debug(
"Response has already been committed. Unable to redirect to "
+ targetUrl);
return;
}
redirectStrategy.sendRedirect(request, response, targetUrl);
}
protected String determineTargetUrl(Authentication authentication) {
boolean isUser = false;
boolean isFreelance = false;
boolean isClient = false;
boolean isAgency = false;
boolean isManager = false;
Collection<? extends GrantedAuthority> authorities
= authentication.getAuthorities();
for (GrantedAuthority grantedAuthority : authorities) {
if (grantedAuthority.getAuthority().equals("ROLE_FREELANCE")) {
isFreelance = true;
break;
} else if (grantedAuthority.getAuthority().equals("ROLE_CLIENT")) {
isClient = true;
break;
} else if (grantedAuthority.getAuthority().equals("ROLE_AGENCY")) {
isAgency = true;
break;
} else if (grantedAuthority.getAuthority().equals("ROLE_MANAGER")) {
isManager = true;
break;
} else if (grantedAuthority.getAuthority().equals("ROLE_USER")) {
isUser = true;
break;
}
}
if (isFreelance) {
return "freelance/homepage.html";
} else if (isClient) {
return "client/homepage.html";
} else if (isAgency) {
return "agency/homepage.html";
} else if (isManager) {
return "manager/homepage.html";
} else if (isUser) {
return "user/homepage.html";
} else {
throw new IllegalStateException();
}
}
protected void clearAuthenticationAttributes(HttpServletRequest request) {
HttpSession session = request.getSession(false);
if (session == null) {
return;
}
session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
}
public void setRedirectStrategy(RedirectStrategy redirectStrategy) {
this.redirectStrategy = redirectStrategy;
}
protected RedirectStrategy getRedirectStrategy() {
return redirectStrategy;
}
}