JUnit4 with Mockito for unit testing - session

public class DgiQtyAction extends DispatchAction {
private final Logger mLog = Logger.getLogger(this.getClass());
public ActionForward fnDgiQty(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
mLog.debug(request.getParameter(EcoConstants.ecopidid));
ActionErrors errorMessage = new ActionErrors();
if(request.getSession().getAttribute(EcoConstants.userBean)==null)
{
request.setAttribute(EcoConstants.ERROR_MESSAGE,EcoConstants.SESSION_TIMEOUT);
errorMessage.add(Globals.MESSAGE_KEY, new ActionMessage(EcoConstants.error_message,EcoConstants.SESSION_TIMEOUT));
saveMessages(request, errorMessage);
request.setAttribute(EcoConstants.errorMessageType,EcoConstants.errorMessageType);
return mapping.findForward(EcoConstants.SESSION_FORWARD);
}
String ecoPidID = (String) request.getParameter(EcoConstants.ecopidid);
String pidId = ESAPI.encoder().encodeForHTML((String) request.getParameter(EcoConstants.pidid));
mLog.debug("pidid --------" + pidId);
mLog.debug("ecopidpid --------" + ecoPidID);
ArrayList dgiQty = new ArrayList();
NeedDgiForm niForm = new NeedDgiForm();
try {
NeedDgiBD niBD = new NeedDgiBD();
if (ecoPidID != null) {
dgiQty = niBD.getDgiQty(ecoPidID);
if (dgiQty.size() != 0) {
mLog.debug(dgiQty.get(0).toString());
if (dgiQty.get(0).toString().equals(EcoConstants.hundred)) {
niForm.setGlqtyList(new ArrayList());
request.setAttribute(EcoConstants.pidId, pidId);
return mapping.findForward(EcoConstants.SuccessInfo);
} else {
mLog.debug("fnBug 1----------------> " + dgiQty.get(0));
mLog.info("dgiQty sizeeeee: :" + dgiQty.size());
niForm.setGlqtyList(dgiQty);
}
}
}
} catch (Exception e) {
//log.error("General Exception in DgiQtyAction.fnDgiQty: "
// + e.getMessage(), e);
request.setAttribute(EcoConstants.ERROR_MESSAGE, e.getMessage());
return mapping.findForward(EcoConstants.ERROR_PAGE);
}
mLog.debug("pidid after wards--------" + pidId);
request.setAttribute(EcoConstants.pidId, pidId);
request.setAttribute(mapping.getAttribute(), niForm);
return mapping.findForward(EcoConstants.SuccessInfo);
}
}
public class DgiQtyActionTest {
ActionMapping am;
ActionForm af;
DgiQtyAction dat;
private MockHttpSession mocksession;
private MockHttpServletRequest mockrequest;
private MockHttpServletResponse mockresponse;
#Test
public void fnDgiQty() throws Exception
{
mocksession = new MockHttpSession();
mockrequest = new MockHttpServletRequest();
mockresponse = new MockHttpServletResponse();
((MockHttpServletRequest) mockrequest).setSession(mocksession);
mocksession.setAttribute("userBean","userBean");
RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(mockrequest));
mockrequest.addParameter("ecopid","something");
mockrequest.addParameter("pid","<script>");
Encoder instance = ESAPI.encoder();
assertEquals("something",mockrequest.getParameter("ecopid"));
assertEquals("<script>",instance.encodeForHTML(mockrequest.getParameter("pid")));
dat=mock(DgiQtyAction.class);
am=mock(ActionMapping.class);
af=mock(ActionForm.class);
dat.fnDgiQty(am,af,mockrequest, mockresponse);
}
}
I wrote the unit test case for above class. i ran this code through jenkins and used sonarqube as code coverage.I need to cover the ESAPi encoder for the parameter, it got build success but the coverage percentage doesn't increase. i couldn't found the mistake in it. pls help me guys. Thanks in Advance

Related

How to change targetSdkVersion

I am having an issue with target targetSdkVersion.I want to move from 27 to 29 but when change to sdk 29 the app runs but does not display videos.But it displays the videos when it is sdk 27 or less.
Please can someone help me fix this.
/**
* A simple {#link Fragment} subclass.
*/
public class ChannelFragment extends Fragment {
private static String GOOGLE_YOUTUBE_API_KEY = "AIzaSyBJQYpQRTzM5wuuhMUxmP7rvP3lbMGtUZ8";//here you should use your api key for testing purpose you can use this api also
private static String CHANNEL_ID = "UCB_ZwuWCAuB7y0B93qvnkWw"; //here you should use your channel id for testing purpose you can use this api also
private static String CHANNLE_GET_URL = "https://www.googleapis.com/youtube/v3/search?part=snippet&order=date&channelId=" + CHANNEL_ID + "&maxResults=50&key=" + GOOGLE_YOUTUBE_API_KEY + "";
private RecyclerView mList_videos = null;
private VideoPostAdapter adapter = null;
private ArrayList<YoutubeDataModel> mListData = new ArrayList<>();
public ChannelFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_channel, container, false);
mList_videos = (RecyclerView) view.findViewById(R.id.mList_videos);
initList(mListData);
new RequestYoutubeAPI().execute();
return view;
}
private void initList(ArrayList<YoutubeDataModel> mListData) {
mList_videos.setLayoutManager(new LinearLayoutManager(getActivity()));
adapter = new VideoPostAdapter(getActivity(), mListData, new OnItemClickListener() {
#Override
public void onItemClick(YoutubeDataModel item) {
YoutubeDataModel youtubeDataModel = item;
Intent intent = new Intent(getActivity(), DetailsActivity.class);
intent.putExtra(YoutubeDataModel.class.toString(), youtubeDataModel);
startActivity(intent);
}
});
mList_videos.setAdapter(adapter);
}
//create an asynctask to get all the data from youtube
private class RequestYoutubeAPI extends AsyncTask<Void, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(Void... params) {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(CHANNLE_GET_URL);
Log.e("URL", CHANNLE_GET_URL);
try {
HttpResponse response = httpClient.execute(httpGet);
HttpEntity httpEntity = response.getEntity();
String json = EntityUtils.toString(httpEntity);
return json;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
if (response != null) {
try {
JSONObject jsonObject = new JSONObject(response);
Log.e("response", jsonObject.toString());
mListData = parseVideoListFromResponse(jsonObject);
initList(mListData);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
public ArrayList<YoutubeDataModel> parseVideoListFromResponse(JSONObject jsonObject) {
ArrayList<YoutubeDataModel> mList = new ArrayList<>();
if (jsonObject.has("items")) {
try {
JSONArray jsonArray = jsonObject.getJSONArray("items");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject json = jsonArray.getJSONObject(i);
if (json.has("id")) {
JSONObject jsonID = json.getJSONObject("id");
String video_id = "";
if (jsonID.has("videoId")) {
video_id = jsonID.getString("videoId");
}
if (jsonID.has("kind")) {
if (jsonID.getString("kind").equals("youtube#video")) {
YoutubeDataModel youtubeObject = new YoutubeDataModel();
JSONObject jsonSnippet = json.getJSONObject("snippet");
String title = jsonSnippet.getString("title");
String description = jsonSnippet.getString("description");
String publishedAt = jsonSnippet.getString("publishedAt");
String thumbnail = jsonSnippet.getJSONObject("thumbnails").getJSONObject("high").getString("url");
youtubeObject.setTitle(title);
youtubeObject.setDescription(description);
youtubeObject.setPublishedAt(publishedAt);
youtubeObject.setThumbnail(thumbnail);
youtubeObject.setVideo_id(video_id);
mList.add(youtubeObject);
}
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
return mList;
}
}

Replace OAuth2AccessTokenJackson2Deserializer with my own custom deserializer

This class is deserializing an oauth2 token and I would like to tweak it. I created my own class extending StdDeserializer<OAuth2AccessToken> which at the moment is the same as the original class.
Here is the class:
public class MyCustomDeserializer extends StdDeserializer<OAuth2AccessToken> {
public MyCustomDeserializer() {
super(OAuth2AccessToken.class);
}
#Override
public OAuth2AccessToken deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException,
JsonProcessingException {
String tokenValue = null;
String tokenType = null;
String refreshToken = null;
Long expiresIn = null;
Set<String> scope = null;
Map<String, Object> additionalInformation = new LinkedHashMap<String, Object>();
// TODO What should occur if a parameter exists twice
while (jp.nextToken() != JsonToken.END_OBJECT) {
String name = jp.getCurrentName();
jp.nextToken();
if (OAuth2AccessToken.ACCESS_TOKEN.equals(name)) {
tokenValue = jp.getText();
}
else if (OAuth2AccessToken.TOKEN_TYPE.equals(name)) {
tokenType = jp.getText();
}
else if (OAuth2AccessToken.REFRESH_TOKEN.equals(name)) {
refreshToken = jp.getText();
}
else if (OAuth2AccessToken.EXPIRES_IN.equals(name)) {
try {
expiresIn = jp.getLongValue();
} catch (JsonParseException e) {
expiresIn = Long.valueOf(jp.getText());
}
}
else if (OAuth2AccessToken.SCOPE.equals(name)) {
scope = parseScope(jp);
} else {
additionalInformation.put(name, jp.readValueAs(Object.class));
}
}
// TODO What should occur if a required parameter (tokenValue or tokenType) is missing?
DefaultOAuth2AccessToken accessToken = new DefaultOAuth2AccessToken(tokenValue);
accessToken.setTokenType(tokenType);
if (expiresIn != null) {
accessToken.setExpiration(new Date(System.currentTimeMillis() + (expiresIn * 1000)));
}
if (refreshToken != null) {
accessToken.setRefreshToken(new DefaultOAuth2RefreshToken(refreshToken));
}
accessToken.setScope(scope);
accessToken.setAdditionalInformation(additionalInformation);
return accessToken;
}
private Set<String> parseScope(JsonParser jp) throws JsonParseException, IOException {
Set<String> scope;
if (jp.getCurrentToken() == JsonToken.START_ARRAY) {
scope = new TreeSet<String>();
while (jp.nextToken() != JsonToken.END_ARRAY) {
scope.add(jp.getValueAsString());
}
} else {
String text = jp.getText();
scope = OAuth2Utils.parseParameterList(text);
}
return scope;
}
}
Here I am registering the bean:
#Bean
public ObjectMapper configObjectMapper() {
final ObjectMapper objectMapper = new ObjectMapper();
objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
final SimpleModule module = new SimpleModule("configModule", com.fasterxml.jackson.core.Version.unknownVersion());
module.addDeserializer(OAuth2AccessToken.class, new MyCustomDeserializer());
objectMapper.registerModule(module);
return objectMapper;
}
Testing the above code the flow doesn't reach my class but the original. I am using spring boot 2.1.4

#Around advice returning correct response but at client side response is null or undefined

I am trying to apply Around advice to my "Login.jsp" with angular js. And the problem is my controller method is check and I am applying around advice to check method but when I run my application I will get undefined as response at Login.jsp. And but the result which I had printed in my advice contains expected result.But I am not getting it on client side.
AroundAdvice.java
#Aspect #Component
public class AroundAdvice {
static Logger log = Logger.getLogger(AfterLoginAspect.class.getName());
#Around("execution(* com.admin.controller.LoginController.check(..))")
public void logWrittter(ProceedingJoinPoint jp) throws Throwable {
SimpleDateFormat date=new SimpleDateFormat();
log.info("Date Time :: " + date.format(new Date().getTime()));
Object result = jp.proceed();
System.out.println("result around");
log.info("result :: " + result);
// returns {"get Status":"home"}
}
}
LoginController.jsp
// authentication check
#RequestMapping(value = "/PostFormData", method = RequestMethod.POST)
public #ResponseBody JSONObject check(#RequestBody LoginBo login) {
System.out.println("checkCredentials::" + login.getUserName());
String username = login.getUserName();
// log.info("uswername ::"+username);
JSONObject result = new JSONObject();
String encrptedpassword = encryptdPwd.encrypt(login.getPassWord());
boolean login_status = loginService.checkCredentials(username, encrptedpassword);
// log.info("login_status ::"+login_status);
// System.out.println("staus ::"+login_status);
if (login_status == true && login.isIs_system_generated_pwd() == true) {
System.out.println("sys gen chnge pwd:: " + login.isIs_system_generated_pwd());
result.put("getStatus", "change");
// System.out.println(resultPage);
// login.setIs_system_generated_pwd(false);
} else if (login_status == true && login.isIs_system_generated_pwd() == false) {
result.put("getStatus", "home");
// System.out.println("Home paege ");
} else {
result.put("getStatus", "error");
}
System.out.println("result ::" + result);
// log.info("result ::"+resultPage);
return result;
}
Your pointcut does not match because the advice has a void return type, but your method returns a JSONObject. So maybe you want to change your advice declaration to:
#Aspect #Component
public class AroundAdvice {
static Logger log = Logger.getLogger(AfterLoginAspect.class.getName());
#Around("execution(* com.admin.controller.LoginController.check(..))")
public JSONObject logWriter(ProceedingJoinPoint jp) throws Throwable {
SimpleDateFormat date=new SimpleDateFormat();
log.info("Date Time :: " + date.format(new Date().getTime()));
JSONObject result = (JSONObject) jp.proceed();
System.out.println("result around");
log.info("result :: " + result);
return result;
}
}
Please note
public JSONObject logWriter instead of public void logWrittter,
JSONObject result = (JSONObject) jp.proceed(); instead of Object result = jp.proceed(); and
return result; instead of no return value.

Using one progressDialog in two or more android stringRequest Volley

In my code I have to stringRequest Volley that works just fine, but now I want to use a progressDialog. I have create 1 method to put the progressDialog like this
private void showProgress(String message) {
progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Loading Data " + message);
progressDialog.setMessage("Please wait...");
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setCancelable(false);
progressDialog.show();
}
and I have these 2 stringRequest like this:
private void fetchDataPoMurni(final String tipe, final String user_id, final String last_date) {
showProgress("Murni");
String tag_string_req = "Request Po Dapat";
StringRequest stringRequest = new StringRequest(
Request.Method.POST,
AppConfig.URL_FETCH_REPORT_PO,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
boolean error = jsonObject.getBoolean("error");
if(!error) {
JSONArray resultPo = jsonObject.getJSONArray("result");
for(int i = 0; i < resultPo.length(); i++) {
JSONObject result = (JSONObject) resultPo.get(i);
String _cabang_id = result.getString("branch_id");
String _area_id = result.getString("areacode");
String _cabang = result.getString("branch_name");
Log.d("FETCHING DATA MURNI: ", _cabang_id + " " + _area_id + " " + _cabang);
dataBaseHelper.insertDataPoMurni(new PoModel(_cabang_id.trim(), _area_id.trim(), _cabang.trim()));
}
} else {
String errorMsg = jsonObject.getString("result");
showAlertDialog(errorMsg);
}
} catch (JSONException e) {
showAlertDialog(e.getMessage());
}
if (progressDialog != null) {
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
showAlertDialog(volleyError.getMessage());
if (progressDialog != null) {
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("tipe", tipe);
params.put("uid", user_id);
params.put("last_date", last_date);
return params;
}
};
AppController.getInstance().addToRequestQueue(stringRequest, tag_string_req);
}
and the other request:
private void fetchDataPoDapat(final String tipe, final String user_id, final String last_date) {
showProgress("Dapat");
String tag_string_req = "Request Po Dapat";
StringRequest stringRequest = new StringRequest(
Request.Method.POST,
AppConfig.URL_FETCH_REPORT_PO,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
boolean error = jsonObject.getBoolean("error");
if(!error) {
JSONArray resultPo = jsonObject.getJSONArray("result");
for(int i = 0; i < resultPo.length(); i++) {
JSONObject result = (JSONObject) resultPo.get(i);
String _cabang_id = result.getString("branch_id");
String _area_id = result.getString("areacode");
String _cabang = result.getString("branch_name");
Log.d("FETCHING DATA DAPAT : ", _cabang_id + " " + _area_id + " " + _cabang);
dataBaseHelper.insertDataPoDapat(new PoModel(_cabang_id.trim(), _area_id.trim(), _cabang.trim()));
}
} else {
String errorMsg = jsonObject.getString("result");
showAlertDialog(errorMsg);
}
} catch (JSONException e) {
showAlertDialog(e.getMessage());
}
if (progressDialog != null) {
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
showAlertDialog(volleyError.getMessage());
if (progressDialog != null) {
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("tipe", tipe);
params.put("uid", user_id);
params.put("last_date", last_date);
return params;
}
};
AppController.getInstance().addToRequestQueue(stringRequest, tag_string_req);
}
I execute the 2 request through a method like this:
private void exeRequest() {
fetchDataPoMurni(valuea,value2,value3);
fetchDataPoDapat(valueb,value2,value3);
}
the progressDialog is showing, and the message is changing, but the problem is when reach the second request the progressDialog doesn't want to dismiss.
Whats wrong with my code above, and how to achieve what I want?
private void showProgress(String message) {
progressDialog=null;// Initialize to null
progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Loading Data " + message);
progressDialog.setMessage("Please wait...");
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setCancelable(false);
progressDialog.show();
}
Try this .. Initialize all instances of the progressDialog to null as soon as you create a new progress dialog

How do I test a Spring controller that returns a ZIP file?

I have a controller that returns a ZIP file. I would like to compare the ZIP file with the expected ZIP, but I'm not sure how to get the file from my result.
Here is what I have so far:
public class FileControllerTest extends ControllerTest {
#InjectMocks
private FileController controller;
#Autowired
private WebApplicationContext context;
private MockMvc mvc;
#Before
public void initTests() throws IOException {
MockitoAnnotations.initMocks(this);
mvc = MockMvcBuilders.webAppContextSetup(context).build();
}
#Test
public void shouldReturnZip() throws Exception {
MvcResult result = mvc
.perform(get(SERVER + FileController.REQUEST_MAPPING + "/zip").accept("application/zip"))
.andExpect(status().isOk()).andExpect(content().contentType("application/zip"))
.andDo(MockMvcResultHandlers.print()).andReturn();
}
}
You can get a byte array from MvcResult .getResponse().getContentAsByteArray().
From there you can convert a ByteArrayInputStream into a File or ZipFile for comparison.
final byte[] contentAsByteArray = mvc.perform(get("/zip-xlsx")
.header(CORRELATION_ID_HEADER_NAME, CID))
.andDo(print())
.andExpect(status().isOk())
.andReturn().getResponse().getContentAsByteArray();
try (final var zin = new ZipInputStream(new ByteArrayInputStream(contentAsByteArray))) {
ZipEntry entry;
String name;
long size;
while ((entry = zin.getNextEntry()) != null) {
name = entry.getName();
size = entry.getSize();
System.out.println("File name: " + name + ". File size: " + size);
final var fout = new FileOutputStream(name);
for (var c = zin.read(); c != -1; c = zin.read()) {
fout.write(c);
}
fout.flush();
zin.closeEntry();
fout.close();
}
} catch (Exception ex) {
System.out.println(ex.getMessage());
}

Resources