how to manage sessions for all test methods in junit - security
i want fetch session details for all test method how to config
when we login we can set session id in the form of cookies. how to manage sessions in jsunit every time after creating mock session also session is null.
#RestController
class LoginContoller{
#PostMapping(value = "/login")
public ResponseEntity\<GenericRes\> login(#RequestBody UserModel userModel) throws Exception {
UserDomain user = userService.login(userModel);
HttpSession session = CommonUtils.geSsession();
if(session!=null)
session.setAttribute("userModel", user);
return prepareSuccessResponse(user);
}
}
this is common utill class where we use to get session and set session
public class CommonUtils implements Constants {
public static HttpSession geSsession() {
ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
ServletRequestAttributes attr1 = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
//if (session == null)
session = attr.getRequest().getSession(true);
return session;
}
}
//service class
#Service
public class VerificationArticleServiceImpl implements VerificationArticleService {
public String verifyArticle(long articleId, boolean verifiedStatus) throws Exception {
UploaderArticleDomain uploaderArticleDomain = uploaderArticleRepository.getByArticleId(articleId);
if (uploaderArticleDomain.getStatus() == ArticleStatusCode.VERIFIED.getCode()) {
throw new Exception(" Article already verified");
}
else if (verifiedStatus) {
uploaderArticleDomain.setStatus(ArticleStatusCode.VERIFIED.getCode());
uploaderArticleRepository.updateArticleStatus(uploaderArticleDomain.getStatus(),
uploaderArticleDomain.getArticleId());
UserDomain userDomain = (UserDomain) CommonUtils.geSsession().getAttribute("userModel");
userService.saveUserLogDetails(userDomain, "Verifying Article", uploaderArticleDomain.getTitle());
String verifierName = userDomain.getFirstName() + userDomain.getLastName();
addVerifiedEntry(uploaderArticleDomain, verifierName);
return "Article Verified";
} else {
throw new Exception("Article is not verified");
}
}
}
here i have used mockhttp session object and try to set attribute but still canot fetch session attribute inside above method.
#RunWith(SpringRunner.class)
#SpringBootTest#AutoConfigureMockMvcpublic class TestVerificationArticleServices {
#Autowired
MockMvc mockMvc;
#Autowired
UploaderArticleService uploaderArticleService;
#MockBean
UploadedArticleRepository uploadedArticleRepository;
#Autowired
CategoryService categoryService;
#MockBean
CategoryRepository categoryRepository;
#Autowired
UploaderArticleMapper uploaderArticleMapper;
#Autowired
UserMapper userMapper;
#Autowired
VerificationArticleService verificationArticleService;
#MockBean
MockHttpSession session;
private List<UploaderArticleDomain> articleList;
private UploaderArticleDomain uploaderOne, uploaderTwo, uploaderThree;
private List<CategoryDomain> categoryList;
private CategoryDomain category1, category2;
private UserDomain userDomain;
#Autowired
UserService userService;
#Mock
CommonUtils commonUtils;
#Autowired
ObjectMapper objectMapper;
#MockBean
UserDAORepository userDAORepository;
#BeforeEach
public void init() {
MockitoAnnotations.openMocks(this);
articleList = new ArrayList<UploaderArticleDomain>();
uploaderOne = new UploaderArticleDomain(1, 1005, "DS", "DS", "DS", "DS", "DS", "DS", 500, "DS", 100, 0, "DS",
"10456", LocalDateTime.now(), LocalDateTime.now(), 0, null, null, null);
uploaderTwo = new UploaderArticleDomain(2, 1006, "DS", "DS", "DS", "DS", "DS", "DS", 500, "DS", 100, 0, "DS",
"10457", LocalDateTime.now(), LocalDateTime.now(), 0, null, null, null);
uploaderThree = new UploaderArticleDomain(3, 1007, "DS", "DS", "DS", "DS", "DS", "DS", 500, "DS", 100, 0, "DS",
"10458", LocalDateTime.now(), LocalDateTime.now(), 0, null, null, null);
articleList.add(uploaderOne);
articleList.add(uploaderTwo);
articleList.add(uploaderThree);
categoryList = new ArrayList<CategoryDomain>();
category1 = new CategoryDomain(1, 100, "Computer", LocalDateTime.now(), LocalDateTime.now());
category2 = new CategoryDomain(2, 101, "IOT", LocalDateTime.now(), LocalDateTime.now());
categoryList.add(category1);
categoryList.add(category2);
userDomain = new UserDomain("1001", "Meghana", "NV", 85487666384L, 85499632484L, "meghana#gmail.com", new AddressDomain("1", "1001", 1, "address1", "address2", "101", "17", "5", new BigInteger("560064"), new BigInteger("456"), "street", LocalDateTime.now(), LocalDateTime.now(), true), new BankDomain(), new RoleDomain(1, "ADMIN", null, null, true, null), "$2a$10$gdgmWEvzS.aSoCWOVmSHt.vnQQ28citzgtwf4SQnnVw0QzvGQTAH2", "11-03-1998", 1, new BigInteger("20282738393"), "app",null, LocalDateTime.now(), LocalDateTime.now(),true, false, null);
}
#Test
public void testPostLogin() throws Exception {
MockitoAnnotations.initMocks(this);
when(userDAORepository.findByEmailId("meghananv1998#gmail.com")).thenReturn(userDomain);
MockHttpServletRequest request=new MockHttpServletRequest();
RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request));
ServletRequestAttributes attributes=mock(ServletRequestAttributes.class);
session =(MockHttpSession) request.getSession();
UserDomain user = new UserDomain();
user.setEmailId("meghananv1998#gmail.com");
user.setPassword("Megha#2022");
UserModel userModel = new UserModel();
BeanUtils.copyProperties(user, userModel);
session.setAttribute("userModel", userModel);
user = userService.login(userModel);
when(CommonUtils.geSsession()).thenReturn(session);
when(uploadedArticleRepository.getByArticleId(1005)).thenReturn(uploaderOne);
verificationArticleService.verifyArticle(1005, true);
}
}
Related
Android Studio How to get session cookies that i requested by post method using Volley
I want to make when i login with id and password in my application which is my univ website account, then application show my profile in the university. And I don't want to use WebView, but Volley(i want get session cookie). So what I want to know is how it works exactly. because I tried with Volley but, it brings JSESSION etc not login session. And it is my LoginActivity.java code that I tried. Ignore Log.d(). package com.tistory.hyomyo.kangnamuniversityapp; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import com.android.volley.AuthFailureError; import com.android.volley.NetworkResponse; 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.StringRequest; import com.android.volley.toolbox.Volley; import com.google.android.material.textfield.TextInputEditText; import java.util.HashMap; import java.util.Map; public class LoginActivity extends AppCompatActivity { public static final String TAG = "LoginActivityTag"; private TextInputEditText textId; private TextInputEditText textPassword; private Button sendBtn; private RequestQueue queue; #Override protected void onCreate(#Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); textId = findViewById(R.id.login_uid); textPassword = findViewById(R.id.login_password); sendBtn = findViewById(R.id.send_btn); queue = Volley.newRequestQueue(this); String url = "https://knusso.kangnam.ac.kr/sso/pmi-sso-login-uid-password.jsp"; final StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() { #Override public void onResponse(String response) { Log.d("Response", response); } }, new Response.ErrorListener() { #Override public void onErrorResponse(VolleyError error) { if(error.networkResponse.statusCode == 302){ Log.d("ErrorResponse",error.networkResponse.allHeaders.toString()); final String url1 = error.networkResponse.headers.get("Location"); String str = error.networkResponse.headers.get("Set-Cookie"); //str = str.substring(str.indexOf("JSESSIONID="),str.indexOf("JSESSIONID=")+"JSESSIONID".length()+32); NetworkResponse networkResponse = requestUrl(url1, str, "TAG", 0); if(networkResponse!=null) Log.d("networkResponse", networkResponse.headers.toString()); else Log.d("networkResponse", "null"); }else if(error.networkResponse.statusCode == 500){ Log.e("WrongPassword","Wrong password Error or Something is wrong: 500"); } } }) { #Override protected Map<String, String> getParams() throws AuthFailureError { Map<String, String> params = new HashMap<String, String>(); // 나중에 예외처리 구현 권장 params.put("gid","gid_web"); params.put("returl", "https://web.kangnam.ac.kr/sso/index.jsp"); params.put("uid", textId.getText().toString()); params.put("password", textPassword.getText().toString()); return params; } #Override protected Response<String> parseNetworkResponse(NetworkResponse response) { Log.i("response",response.headers.toString()); Map<String, String> responseHeaders = response.headers; String rawCookies = responseHeaders.get("Set-Cookie"); Log.i("cookies",rawCookies); return super.parseNetworkResponse(response); } }; stringRequest.setTag(TAG); sendBtn.setOnClickListener(view -> { queue.add(stringRequest); }); } private NetworkResponse requestUrl(final String url, final String Cookie, String tag, int i){ final NetworkResponse[] ret = {null}; Log.d("요청유알엘", url); final StringRequest request = new StringRequest(Request.Method.GET, url, response -> { Log.d("응답하라", url); }, error -> { Log.d("URL", url); Log.d("Cookie", Cookie); Log.d("ERROR", error.toString()); if(error. networkResponse. statusCode == 302){ final String url2 = error.networkResponse.headers.get("Location"); ret[0] = requestUrl(url2, Cookie, tag+i, i+1); }else{ Log.d("Other Error Code", error.networkResponse.statusCode+""); ret[0] = error.networkResponse; } }){ #Override public Map<String, String> getHeaders() throws AuthFailureError { Map<String, String> params = new HashMap<>(); params.put("Cookie", Cookie); return params; } #Override protected Response<String> parseNetworkResponse(NetworkResponse response) { if (response == null) { Log.d("응답됨", "null"); super.parseNetworkResponse(response); }Log.d("응답됨", response.headers.get("Set-Cookie")); ret[0] = response; return super.parseNetworkResponse(response); } }; request.setTag(tag); queue.add(request); return ret[0]; } #Override protected void onStop() { super.onStop(); if(queue!=null){ queue.cancelAll(TAG); queue.cancelAll("TAG"); queue.cancelAll("TAG0"); queue.cancelAll("TAG1"); queue.cancelAll("TAG2"); queue.cancelAll("TAG3"); } } public void logLargeString(String str){ if(str.length() > 3000){ Log.i(TAG, str.substring(0, 3000)); logLargeString(str.substring(3000)); }else{ Log.i(TAG, str); } } }
to invoke interface method 'retrofit2.Call on a null object reference
how can i solve null object while sending post request error says to invoke interface method 'retrofit2.Call com.itgrepnet.foodbundle.remote.UserService.addUser(com.itgrepnet.foodbundle.model.User)' on a null object reference in AddUserActivity btnSubmit.setOnClickListener(new View.OnClickListener() { #Override public void onClick(View view) { addNewUser(); } private void addNewUser() { User u = new User(); u.setFirstname(first_name.getText().toString()); u.setLastname(last_name.getText().toString()); u.setEmail(email.getText().toString()); u.setPassword(password.getText().toString()); Call<User> call = userService.addUser(u); call.enqueue(new Callback<User>() { #Override public void onResponse(Call<User> call, Response<User> response) { if (response.isSuccessful()) { Toast.makeText(getApplicationContext(), "User Created Successfully!", Toast.LENGTH_LONG).show(); } } #Override public void onFailure(Call<User> call, Throwable t) { Log.e("Error: ", t.getMessage()); } }); } }); UserService.java #POST("user/") Call<User> addUser(#Body User user); RetrofitClient.java public class RetrofitClient { private static Retrofit retrofit = null; public static Retrofit getClient(String url) { if (retrofit == null) { retrofit = new Retrofit.Builder().baseUrl(url) .addConverterFactory(GsonConverterFactory.create()) .build(); } return retrofit; } }
CustomDestination gives Guava cache Error
We have overwritten AbstractDestinationFacade with our implementation of DestinationFacade and Destination. When we try to connect over this destination we get a runtime Exception from Guava cache Our use case:: We are trying to connect to remote systems from NonCF platforms. Our Local Implementations are as shown below LocalDestinationFacade public class LocalDestinationFacade extends AbstractDestinationFacade { #Override public Class<? extends GenericDestination> getGenericDestinationClass() { // TODO Auto-generated method stub return null; } #Override public Class<? extends Destination> getDestinationClass() { // TODO Auto-generated method stub return LocalDestination.class; } #Override public Class<? extends RfcDestination> getRfcDestinationClass() { // TODO Auto-generated method stub return null; } #Override public Map<String, GenericDestination> getGenericDestinationsByName() throws DestinationAccessException { Destination localDestination=new LocalDestination("AniPremise", "https://custom-backend-corp/",AuthenticationType.BASIC_AUTHENTICATION,new BasicCredentials("adas", "adas")); Map<String, GenericDestination> destinations=new HashMap<>(); destinations.put("AniPremise", localDestination); return destinations; } } LocalDestination public class LocalDestination extends AbstractDestination { public LocalDestination(String name, String description, String uri, AuthenticationType authenticationType, BasicCredentials basicCredentials, ProxyType proxyType, ProxyConfiguration proxyConfiguration, boolean isTrustingAllCertificates, String trustStoreLocation, String trustStorePassword, String keyStoreLocation, String keyStorePassword, Map<String, String> propertiesByName) { super(name, description, uri, authenticationType, basicCredentials, proxyType, proxyConfiguration, isTrustingAllCertificates, trustStoreLocation, trustStorePassword, keyStoreLocation, keyStorePassword, propertiesByName); } public LocalDestination(String name,String uri) { this(name, null, uri, null, null, null, null, true, null, null, null, null, Collections.emptyMap()); } public LocalDestination(String name,String uri,AuthenticationType authenticationType,BasicCredentials basicCredentials) { this(name, null, uri, authenticationType, basicCredentials,ProxyType.INTERNET , null, false, null, null, null, null, Collections.emptyMap()); } #Override public Optional<KeyStore> getTrustStore() throws DestinationAccessException { return null; } #Override public Optional<KeyStore> getKeyStore() throws DestinationAccessException { return null; } } The following stacktrace is produced when we query against the destination. com.google.common.util.concurrent.UncheckedExecutionException: java.lang.NullPointerException at com.google.common.cache.LocalCache$Segment.get(LocalCache.java:2051) at com.google.common.cache.LocalCache.get(LocalCache.java:3953) at com.google.common.cache.LocalCache$LocalManualCache.get(LocalCache.java:4873) at com.sap.cloud.sdk.cloudplatform.connectivity.HttpClientCache.getHttpClient(HttpClientCache.java:51) at com.sap.cloud.sdk.cloudplatform.connectivity.HttpClientAccessor.getHttpClient(HttpClientAccessor.java:148) at com.sap.cloud.sdk.cloudplatform.connectivity.HttpClientAccessor.getHttpClient(HttpClientAccessor.java:128) at com.sap.cloud.sdk.odatav2.connectivity.ODataQuery.internalExecute(ODataQuery.java:242) at com.sap.cloud.sdk.odatav2.connectivity.ODataQuery.execute(ODataQuery.java:178) at com.sap.cloud.sdk.odatav2.connectivity.ODataQuery.execute(ODataQuery.java:227) at com.sap.cloud.sdk.odatav2.connectivity.ODataQuery.execute(ODataQuery.java:201) at com.sap.cloud.sdk.s4hana.datamodel.odata.helper.FluentHelperRead.execute(FluentHelperRead.java:244) at com.sap.gb.s4backend.dataprovider.S4HanaDataProviderImpl.getPurchaseRequisitionWorkList(S4HanaDataProviderImpl.java:473) at com.sap.gb.odata.provisioning.GBOdataRequestProcessor.readEntitySet(GBOdataRequestProcessor.java:102)
The problem with add 2nd datasource with mybatis ORM in jhipster 5.7.2 project
The problem with add 2nd datasource with mybatis ORM in jhipster 5.7.2 project 1、add configuration MatchingDatabaseConfiguration.java #Configuration #EnableTransactionManagement #EntityScan(basePackages = "sample.mybatis.domain") #MapperScan(basePackages = "sample.mybatis.dao", sqlSessionTemplateRef = "matchingSqlSessionTemplate") public class MatchingDatabaseConfiguration { private String localMapper = "classpath:mappers/*.xml"; #Bean #ConfigurationProperties("application.datasource") public DataSourceProperties matchingDataSourceProperties() { return new DataSourceProperties(); } #Bean(name = "matchingDataSource") #ConfigurationProperties("application.datasource") public DataSource matchingDataSource() { return matchingDataSourceProperties().initializeDataSourceBuilder().build(); } #Bean(name = "matchingTransactionManager") public DataSourceTransactionManager matchingTransactionManager() { return new DataSourceTransactionManager(matchingDataSource()); } #Bean(name = "matchingSqlSessionFactory") public SqlSessionFactory matchingSqlSessionFactory() throws Exception { final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean(); sessionFactory.setDataSource(matchingDataSource()); sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver(). getResources(localMapper)); return sessionFactory.getObject(); } #Bean(name = "matchingSqlSessionTemplate") public SqlSessionTemplate buildSqlSessionTemplate(#Qualifier("matchingSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception { return new SqlSessionTemplate(sqlSessionFactory); } #Bean(name = "matchingTransaction") public PlatformTransactionManager matchingTransactionManager(#Qualifier("matchingDataSource") DataSource dataSource) { return new DataSourceTransactionManager(dataSource); } } 2 application-dev.yml application: datasource: type: com.zaxxer.hikari.HikariDataSource url: jdbc:mysql://localhost:3306/mytest?useUnicode=true&characterEncoding=utf8&useSSL=false username: root password: 3 ApplicationProperties.java add properties field https://github.com/jnuc093/xpdjh/blob/master/src/main/java/com/isunland/app/config/ApplicationProperties.java 4 add the mybatis sample xml files https://github.com/jnuc093/xpdjh/tree/master/src/main/resources/mappers 5 add sample.mybatis package https://github.com/jnuc093/xpdjh/tree/master/src/main/java/sample/mybatis 6 add Controller #RestController #RequestMapping("/api") public class CityResource { #Autowired private CityDao cityDao; #Autowired private HotelDao hotelDao; #GetMapping("/test-mybatis/{cityId}") public Hotel run(#PathVariable int cityId) { return hotelDao.selectByCityId(cityId); } } 7 The official mybatis sample is here https://github.com/mybatis/spring-boot-starter/tree/master/mybatis-spring-boot-samples/mybatis-spring-boot-sample-xml When i access http://localhost:9000/api/test-mybatis/123 Response Body { "type": "https://www.jhipster.tech/problem/problem-with-message", "title": "Internal Server Error", "status": 500, "detail": "Could not find result map sample.mybatis.dao.CityDao.City", "path": "/api/test-mybatis/123", "message": "error.http.500" } How can i fix this problem
Listview with multiple lists
One list: ListView list = (ListView) pane.lookup("#list"); ObservableList<String> countries = FXCollections.observableArrayList( "England", "Germany", "France", "Israel"); list.setItems(countries); Please tell me how to do like this? ListView list = (ListView) root.lookup("#list"); ObservableList<String> countries = FXCollections.observableArrayList( "England", "Germany", "France", "Israel"); ObservableList<String> capitals = FXCollections.observableArrayList( "London", "Berlin", "Paris", "Ierusalim");
There is an example for you. Just make a bean with country and capital field. And you will have a ListView of YourBean. Like that : The bean public class MyBean { private String country; private String capital; public MyBean(String country, String capital) { this.country = country; this.capital = capital; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public String getCapital() { return capital; } public void setCapital(String capital) { this.capital = capital; } } and the ListView public class Example extends ListView<MyBean> { public Example() { this.getItems().add(new MyBean("France", "Paris")); this.getItems().add(new MyBean("England", "London")); this.setCellFactory(new Callback<ListView<MyBean>, ListCell<MyBean>>() { #Override public ListCell<MyBean> call(ListView<MyBean> myBeanListView) { return new ListCell<MyBean>() { #Override protected void updateItem(MyBean myBean, boolean b) { super.updateItem(myBean, b); if (!b) { HBox box = new HBox(); box.setSpacing(50); box.getChildren().add(new Label(myBean.getCountry())); box.getChildren().add(new Label(myBean.getCapital())); setGraphic(box); } else { setGraphic(null); } } }; } }); } } You just have to adapt it to your program but it for show you the good setCellFactory method