I am newbie in struts2.
In interceptor how can i change value of form field and then submitting it to database?
For example when user enters firstName value in form then when it submits i want to change firstName and then submit it to database.
Here is my interceptor's code
public class TestInterceptor extends AbstractInterceptor implements Interceptor
{
#Override
public String intercept(ActionInvocation actionInvocation) throws Exception
{
ValueStack stack = actionInvocation.getStack();
Map<String, Object> params = ActionContext.getContext().getParameters();
Set<String> keys = params.keySet();
System.out.println(keys + " " + stack.size());
/*
* for (String key : keys)
* {
* String[] value = (String[]) params.get(key);
* System.out.println(value.length + " , " + value[0]);
* }
*/
Map<String, Object> context = new HashMap<String, Object>();
context.put("firstNames", "Changed");
context.put("firstName", "Changed");
stack.setParameter("firstName", "Changeds");
stack.push(context);
String result = actionInvocation.invoke();
return result;
}
}
In your code simply you need to change value in the map. no need to put any other context.
Map<String, Object> params = actionInvocation.getInvocationContext().getParameters();
params.put("firstName", "Changed");
Try this:
public String intercept(ActionInvocation invocation) throws Exception {
final ActionContext context = invocation.getInvocationContext();
Map<String,Object> parameters = (Map<String,Object>)context.get(ActionContext.PARAMETERS);
Map<String, Object> parametersCopy = new HashMap<String, Object>();
parametersCopy.putAll(parameters);
parametersCopy.put("myParam", "changedValue");
context.put(ActionContext.PARAMETERS, parametersCopy);
return invocation.invoke();
}
Related
I'm trying to retrieve subscribers to a price object. Here's my approach, which works:
public void getSubscriptions() throws StripeException {
Stripe.apiKey = KEY;
Map<String, Object> params = new HashMap<>();
Iterable<Subscription> subscrips = Subscription.list(params).autoPagingIterable();
for(Subscription s : subscrips){
if((s.getItems().getData().get(0).getPlan().getId()).equals("price_ABC123")){
System.out.println(s);
}
}
//System.out.println(subscriptions);
}
The issue with this code is that its a bit slow. Is there a more efficient way to retrieve this info?
Thanks
Yes you can filter by price id as shown here https://site-admin.stripe.com/docs/api/subscriptions/list#list_subscriptions-price
public void getSubscriptions() throws StripeException {
Stripe.apiKey = KEY;
Map<String, Object> params = new HashMap<>();
params["price"] = "price_ABC123";
Iterable<Subscription> subscrips = Subscription.list(params).autoPagingIterable();
for(Subscription s : subscrips){
System.out.println(s);
}
}
I want one JSONObject response after passing URI through RESTTemplate
Test case is passing but the code coverage is still 0%
I have to return accountDetails object in JSON format
how do we Pass URI which takes account ID and given response entity in JSON Format this is what I have to figure out.
Test method:
void scheduleOnDemand() throws Exception {
AccountDTO accountDTO = new AccountDTO();
accountDTO.setId(1);
accountDTO.setTimeZone("Asia/Kolkata");
accountDTO.setPlatformType("AZURE");
accountDTO.setEnvironmentName("test");
accountDTO.setName("azureAccount");
accountDTO.setNextScheduleDate("2021-09-13");
accountDTO.setEnvironmentId(1);
HashMap<String, Object> accountDetails = new HashMap<>();
accountDetails.put("account_Id", "1");
accountDetails.put("TimeZone", "Asia/Kolkata");
accountDetails.put("AgentStatus", "Initiated");
accountDetails.put("Account_Platform", "AZURE");
accountDetails.put("Schedule_Time", "13:30:50.000");
accountDetails.put("Environment_Name", "test");
accountDetails.put("Account_Name", "azureAccount");
accountDetails.put("History_Id", "109");
accountDetails.put("Schedule_Date", "2021-09-13");
accountDetails.put("Environment_Id", "1");
Mockito.when(restTemplate.postForEntity("configure/accountDetails?Account_Id=1",null, JSONObject.class))
.thenReturn(new ResponseEntity((accountDetails), HttpStatus.OK));
}
Actual Method:
#Override
public JSONObject scheduleOnDemand(String accountId) throws Exception {
JSONObject object = null;
// PlatformHistoryDetails phistory = null;
HashMap<String, Object> accountDetails = new HashMap<>();
accountDetails = utilService.getAccountDetails(Integer.parseInt(accountId));
if (((String) accountDetails.get("scantype")).equalsIgnoreCase("infra")||((String) accountDetails.get("scantype")).equalsIgnoreCase("all")) {
URI postUri = UriComponentsBuilder.fromPath("/").pathSegment("api/scheduleOnDemand")
.queryParam("requestId", MDC.get("requestId")).queryParam("service", "scan")
.queryParam("Account_Id", accountId).build().toUri();
PlatformHistoryDetails phistory = modelMapper.map(apiClient.postOperation(postUri, Object.class),
PlatformHistoryDetails.class);
phistory.getHistory().setUser("admin");
object = utilService.processOneAccount(phistory);
} else {
throw new Exception("Account is not of type INFRA or ALL but of type " + accountDetails.get("scantype"));
}
return object;
}
accountDetails Implementation:
#Override
#SuppressWarnings({ "unchecked", "rawtypes" })
public HashMap<String, Object> getAccountDetails(int accountId) {
URI getUri = UriComponentsBuilder.fromPath("/").pathSegment("configure/accountDetails")
.queryParam("Account_Id", accountId).build().toUri();
HashMap<String, Object> account = (LinkedHashMap) apiClient.getAccountDetails(getUri, Object.class);
return account;
}
In my Spring Boot project I want to create a URL by concatenating several strings.
The first strings I know how to get them, but to these I have to add some fields defined in a map.
How do I get from this map the list of its keys and for each key add the name of the key with its respective value?
This is the part of the code where I stopped:
#Value("${spring.route.source.protocol}")
private String protocol;
#Value("${spring.route.source.ip}")
private String ip;
#Value("${spring.route.source.root}")
private String root;
#Value("${spring.route.source.gets}")
private List<String> gets;
public void getWithRestTemplateGet1(Map<String, String> allGateAccessParams) {
final String methodName = "getWithRestTemplateGet1()";
try {
startLog(methodName);
List<String> keys = new ArrayList<String>();
//HOW CAN I ADD KEY E VALUE FROM MAP TO URL?
String url = protocol + ip + root + gets.get(0);
HttpHeaders headers = new HttpHeaders();
headers.setBasicAuth(username, password);
HttpEntity request = new HttpEntity(headers);
try {
if (url.startsWith("https")) {
restTemplate = getRestTemplateForSelfSsl();
} else {
restTemplate = new RestTemplate();
}
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, request, String.class);
HttpStatus statusCode = response.getStatusCode();
logger.info("STATUS GET1: " + statusCode);
logger.info("URL GET1: " + url);
logger.info("RESPONSE GET1: " + response);
} catch (HttpStatusCodeException e) {
logger.error(e.getMessage());
}
endLog(methodName);
} catch (Exception e) {
logger.error(e.getMessage());
}
}
Can you help me?
You can get entrySet() from map and iterate entrySet to getKey using getKey() and value using getValue() as below
for (Map.Entry<String, String> entry : allGateAccessParams.entrySet()) {
System.out.println(entry.getKey() + ":" + entry.getValue());
}
Here is a snippet using stream's reduce:
import java.text.MessageFormat;
import java.util.HashMap;
class Scratch {
public static void main(String[] args) {
HashMap<String, String> urlParamsMap = new HashMap<>();
urlParamsMap.put("key1", "value1");
urlParamsMap.put("key2", "value2");
urlParamsMap.put("key3", "value3");
String params = urlParamsMap.entrySet().stream()
.map(entry -> MessageFormat.format("{0}={1}", entry.getKey(), entry.getValue()))
.reduce((accumulator, next) -> MessageFormat.format("{0}{1}{2}",
accumulator,
accumulator.isEmpty() ? "" : "&",
next)
).orElse("");
System.out.println("URL params: " + params);
}
}
First we transform the stream of map entries to a stream of strings. Then we reduce the stream of strings to a single string containing the concatenation of all the strings. Finally it returns an empty string in case that the initial stream was empty. In this example, the result is:
URL params: key1=value1&key2=value2&key3=value3
For more info about how to use stream's reduce this post is very useful.
I wrote a small program that reads from a text file based on supplied user type Admin/ Customer and prints single id and password, which is working. Code below
public class TextReader {
//A method to load properties file
public static Properties readProp() throws IOException {
Properties prop = new Properties();
FileInputStream file = new FileInputStream("C:\\Users\\config.text");
prop.load(file);
return prop;
}
//Read the file using method above
public static void getUser(String userType) throws IOException {
Properties prop = readProp();
String userName=prop.getProperty(userType+ "_User");
String userPassword=prop.getProperty(userType+ "_Psd");
System.out.println(" The user is " + userName + " password " + userPassword);
}
public static void main(String[] args) throws IOException {
getUser("Admin");
}
}
Test file:
Admin_User=jjones#adm.com
Admin_Psd=test123
Cust_User=kim#cust.com
Cust_Psd=test123
I wanted to modify it so that I can now add those to a HashMap. So I removed the userType argument
public static void getUser() throws IOException {
Properties prop = readProp();
String userName = prop.getProperty("_User");
String userPassword = prop.getProperty("_Psd");
HashMap<String, String> hmp = new HashMap<String, String>();
hmp.put(userName, userPassword);
for (Map.Entry<String, String> credentials : hmp.entrySet()) {
System.out.println(credentials.getKey() + " " + credentials.getValue());
}
//System.out.println(" The user is " + userName + " password " + userPassword);
}
I get null null as output. I cannot think of a way to get them in HashMap, I can use some hint/help.
Expected output: user name, password as key value pair
jjones#adm.com test123
kim#cust.com test123
To convert a Properties object to a HashMap<String, String>, copy all the entries:
HashMap<String, String> hmp = new HashMap<>();
for (String name : prop.stringPropertyNames())
hmp.put(name, prop.getProperty(name));
If the properties file can contain other properties, filter while copying, e.g.
HashMap<String, String> hmp = new HashMap<>();
for (String name : prop.stringPropertyNames())
if (name.endsWith("_User") || name.endsWith("_Psd"))
hmp.put(name, prop.getProperty(name));
Or the same using regex:
Pattern suffix = Pattern.compile("_(User|Psd)$");
HashMap<String, String> hmp = new HashMap<>();
for (String name : prop.stringPropertyNames())
if (suffix.matcher(name).find())
hmp.put(name, prop.getProperty(name));
I get error in following lines.
error: incompatible types
required : java.util.Map.entry<java.lang.String,java.lang.String[]>
found :java.lang.Object
full code is below
package com.auth.actions;
public class SocialAuthSuccessAction extends Action {
final Log LOG = LogFactory.getLog(SocialAuthSuccessAction.class);
#Override
public ActionForward execute(final ActionMapping mapping,
final ActionForm form, final HttpServletRequest request,
final HttpServletResponse response) throws Exception {
AuthForm authForm = (AuthForm) form;
SocialAuthManager manager = null;
if (authForm.getSocialAuthManager() != null) {
manager = authForm.getSocialAuthManager();
}
if (manager != null) {
List<Contact> contactsList = new ArrayList<Contact>();
Profile profile = null;
try {
Map<String, String> paramsMap = new HashMap<String, String>();
for (Map.Entry<String, String[]> entry :request.getParameterMap().entrySet() ) { // error in this line!
String key = entry.getKey();
String values[] = entry.getValue();
paramsMap.put(key, values[0].toString()); // Only 1 value is
}
AuthProvider provider = manager.connect(paramsMap);
profile = provider.getUserProfile();
contactsList = provider.getContactList();
if (contactsList != null && contactsList.size() > 0) {
for (Contact p : contactsList) {
if (StringUtils.isEmpty(p.getFirstName())
&& StringUtils.isEmpty(p.getLastName())) {
p.setFirstName(p.getDisplayName());
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
request.setAttribute("profile", profile);
request.setAttribute("contacts", contactsList);
return mapping.findForward("success");
}
// if provider null
return mapping.findForward("failure");
}
}
Please help
You need to cast request.getParameterMap()to Map<String, String[]>
for (Map.Entry<String, String[]> entry :
((Map<String, String[]>)request.getParameterMap()).entrySet())
Try the following:
for (Object obj :request.getParameterMap().entrySet() ) {
Map.Entry<String, String[]> entry = (Map.Entry<String, String[]>) obj;
String key = entry.getKey();
String values[] = entry.getValue();
paramsMap.put(key, values[0].toString()); // Only 1 value is
}
Am not really sure this will work, anyway, you got the approach. Hope this helps.
As pointed out in the comments, getParameterMap() must be returning the raw type Map instead of Map<String, String[]>. This means getParameterMap().entrySet() returns raw Iterable, causing the compiler error.
If you want to avoid doing an explicit unchecked cast as the other answers suggest, an alternative is to use a variable assignment for unchecked conversion:
#SuppressWarnings("unchecked") // getParameterMap returns raw Map
Map<String, String[]> params = request.getParameterMap();
for (Map.Entry<String, String[]> entry : params.entrySet()) {
...
}