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);
}
}
Related
I have two url calls in one method that is in addnewMap() - one is the buildGetSubtenantsURL and the other is buildGetAssetsURL
public void addNewMap(MapDTO mapDTO) {
log.info("going to add the map data into db");
if (mapRepository.existsMapWithMapName(mapDTO.getMapName()))
throw new BadRequestException("Map with map name " + mapDTO.getMapName()
+ " already exists. Please provide a different map name.");
Map<String, String> subtenantInfoMap = new HashMap<>();
Maps mapEntity = new Maps();
String iottenant = mapDTO.getTenant();
String subtenantsURL = buildGetSubtenantsURL(null);
String subTenantsResponse = getSubtenants(subtenantsURL,iottenant);
JSONObject subTenant = getSubtenantName(subTenantsResponse);
checkForMultiplePagesSubtenants(subTenantsResponse, subtenantInfoMap,iottenant);
if(subtenantInfoMap.get(mapDTO.getSubtenantName()) != null) {
mapEntity = Maps.builder().subtenant(subtenantInfoMap.get(mapDTO.getSubtenantName()).toString()).build();
}
else {
throw new DataNotFoundException(SUBTENANT_DOESNT_EXIST);
}
String SubtenantId = subtenantInfoMap.get(mapDTO.getSubtenantName());
UriComponents assetsURL = buildGetAssetsURL(iottenant,SubtenantId);
String assetsResponse = getAssets(assetsURL, iottenant);
String mindsphereAssetId = getAssetId(assetsResponse);
if(mindsphereAssetId.isEmpty()) {
throw new DataNotFoundException(ASSET_ID_DOESNT_EXIST);
}
else {
mapEntity = Maps.builder().mindsphereAssetId(mindsphereAssetId).build();
}
mapEntity = Maps.builder().mapName(mapDTO.getMapName()).displayName(getDisplayName(mapDTO))
.description(Objects.nonNull(mapDTO.getDescription()) ? mapDTO.getDescription() : null)
.tenant(getTenantNameForMapDTO(mapDTO)).mindsphereAssetId(mindsphereAssetId).subtenant(subtenantInfoMap.get(mapDTO.getSubtenantName()).toString())
.mapLocation(mapDTO.getMapLocation()).operator(mapDTO.getOperator()).recipeName(mapDTO.getRecipeName()).subtenantName(mapDTO.getSubtenantName())
.createdBy(getUserEmail()).createdAt(new Timestamp(System.currentTimeMillis()))
.build();
Maps createdMap = mapRepository.saveAndFlush(mapEntity);
addStationsMappingforNewMap(createdMap);
}
I have written the test case for the above method as:
#Test
public void addNewMap() {
map = Maps.builder().mapId(1l).mapName("testMap").displayName("Map Test").mindsphereAssetId("a0609ebf2eb7400da8a5fd707e7f68b7").mapLocation("hyd").operator("operator").recipeName("recipe").subtenantName("NSTI").tenant("ctlbrdev").subtenant("9b04027dde5fbd047073805ab8c1c87c")
.tenant(Tenant).build();
maps = Arrays.asList(map);
mapDTO = MapDTO.builder().mapId(1l).mapName("testMap").displayName("Map Test").subtenantName("NSTI").mapLocation("hyd").recipeName("recipe").operator("operator").description("description")
.tenant("ctlbrdev").build();
ReflectionTestUtils.setField(mapService, "mindsphereBaseURL", MindsphereBaseURL);
ReflectionTestUtils.setField(mapService, "mindsphereSubtenantsURL", mindsphereSubtenantsURL);
ReflectionTestUtils.setField(mapService, "mindsphereAssetsURL", mindsphereAssetsURL);
when(restTemplate.exchange(ArgumentMatchers.anyString(), ArgumentMatchers.any(HttpMethod.class), ArgumentMatchers.any(HttpEntity.class),
ArgumentMatchers.<Class<String>>any()))
.thenReturn(new ResponseEntity<String>(entityDtoCreaters.getSubtenant(),HttpStatus.OK));
when(tokenCaching.retrieveHeadersContainingTechToken("ctblrdev")).thenReturn(new HttpHeaders());
when(mapRepository.existsMapWithMapName(any())).thenReturn(false);
//doReturn(Tenant).when(mapService).getTenantName();
doReturn(EMAIL).when(mapService).getUserEmail();
when(mapRepository.saveAndFlush(any())).thenReturn(map);
when(restTemplate.exchange(ArgumentMatchers.anyString(), ArgumentMatchers.any(HttpMethod.class), ArgumentMatchers.any(HttpEntity.class),
ArgumentMatchers.<Class<String>>any()))
.thenReturn(new ResponseEntity<String>(entityDtoCreaters.getSubtenant(),HttpStatus.OK));
Map<String, String> subtenantInfoMap = new HashMap<>();
subtenantInfoMap.get(mapDTO.getSubtenantName());
mapService.addNewMap(mapDTO);
It is not covering the getAssets() method, hence not covering the whole method. how can I achieve this?
I want to get a list of objects from database
i'm 100% that i retreive the data but the list so my php code seems to be good
public ArrayList<Categorie> getListCategorie() {
ArrayList<Categorie> listcategories = new ArrayList<>();
ConnectionRequest con2 = new ConnectionRequest();
con2.setUrl("http://localhost/pidev2017/selectcategorie.php");
con2.addResponseListener(new ActionListener<NetworkEvent>() {
#Override
public void actionPerformed(NetworkEvent evt) {
try {
JSONParser j = new JSONParser();
Map<String, Object> catefories = j.parseJSON(new CharArrayReader(new String(con2.getResponseData()).toCharArray()));
List<Map<String, Object>> list = (List<Map<String, Object>>) catefories.get("Categorie");
for (Map<String, Object> obj : list) {
Categorie categorie = new Categorie();
categorie.setId(Integer.parseInt(obj.get("id").toString()));
categorie.setNomCategorie(obj.get("nomCategorie").toString());
listcategories.add(categorie);
}
} catch (IOException ex) {
}
}
});
NetworkManager.getInstance().addToQueue(con2);
return listcategories;
}
when i want to fetch my result "listcategories" i found that is empty
Change
NetworkManager.getInstance().addToQueue(con2);
to
NetworkManager.getInstance().addToQueueAndWait(con2);
It's possible that you try to get the result before the data has been fetched.
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();
}
I wrote a simple recursive web crawler to fetch just the URL links from the web page recursively.
Now I am trying to figure out a way to limit the crawler using depth but I am not sure how to limit the crawler by specific depth (I can limit the crawler by top N links but I want to limit using depth)
For Ex: Depth 2 should fetch Parent links -> children(s) links--> children(s) link
Any inputs is appreciated.
public class SimpleCrawler {
static Map<String, String> retMap = new ConcurrentHashMap<String, String>();
public static void main(String args[]) throws IOException {
StringBuffer sb = new StringBuffer();
Map<String, String> map = (returnURL("http://www.google.com"));
recursiveCrawl(map);
for (Map.Entry<String, String> entry : retMap.entrySet()) {
sb.append(entry.getKey());
}
}
public static void recursiveCrawl(Map<String, String> map)
throws IOException {
for (Map.Entry<String, String> entry : map.entrySet()) {
String key = entry.getKey();
Map<String, String> recurSive = returnURL(key);
recursiveCrawl(recurSive);
}
}
public synchronized static Map<String, String> returnURL(String URL)
throws IOException {
Map<String, String> tempMap = new HashMap<String, String>();
Document doc = null;
if (URL != null && !URL.equals("") && !retMap.containsKey(URL)) {
System.out.println("Processing==>" + URL);
try {
URL url = new URL(URL);
System.setProperty("http.proxyHost", "proxy");
System.setProperty("http.proxyPort", "port");
doc = Jsoup.connect(URL).get();
if (doc != null) {
Elements links = doc.select("a");
String FinalString = "";
for (Element e : links) {
FinalString = "http:" + e.attr("href");
if (!retMap.containsKey(FinalString)) {
tempMap.put(FinalString, FinalString);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
retMap.put(URL, URL);
} else {
System.out.println("****Skipping URL****" + URL);
}
return tempMap;
}
}
EDIT1:
I thought of using worklist hence modified the code. I am not exactly sure how to set depth here too (I can set the number of webpages to crawl but not exactly depth). Any suggestions would be appreciated.
public void startCrawl(String url) {
while (this.pagesVisited.size() < 2) {
String currentUrl;
SpiderLeg leg = new SpiderLeg();
if (this.pagesToVisit.isEmpty()) {
currentUrl = url;
this.pagesVisited.add(url);
} else {
currentUrl = this.nextUrl();
}
leg.crawl(currentUrl);
System.out.println("pagesToVisit Size" + pagesToVisit.size());
// SpiderLeg
this.pagesToVisit.addAll(leg.getLinks());
}
System.out.println("\n**Done** Visited " + this.pagesVisited.size()
+ " web page(s)");
}
Based on the non-recursive approach:
Keep a worklist of URLs pagesToCrawl of type CrawlURL
class CrawlURL {
public String url;
public int depth;
public CrawlURL(String url, int depth) {
this.url = url;
this.depth = depth;
}
}
initially (before entering the loop):
Queue<CrawlURL> pagesToCrawl = new LinkedList<>();
pagesToCrawl.add(new CrawlURL(rootUrl, 0)); //rootUrl is the url to start from
now the loop:
while (!pagesToCrawl.isEmpty()) { // will proceed at least once (for rootUrl)
CrawlURL currentUrl = pagesToCrawl.remove();
//analyze the url
//updated with crawled links
}
and the updating with links:
if (currentUrl.depth < 2) {
for (String url : leg.getLinks()) { // referring to your analysis result
pagesToCrawl.add(new CrawlURL(url, currentUrl.depth + 1));
}
}
You could enhance CrawlURL with other meta data (e.g. link name, referrer,. etc.).
Alternative:
In my upper comment I mentioned a generational approach. Its a bit more complex than this one. The basic Idea is to keep to lists (currentPagesToCrawl and futurePagesToCrawl) together with a generation variable (starting with 0 and increasing every time currentPagesToCrawl gets empty). All crawled urls are put into the futurePagesToCrawl queue and if currentPagesToCrawl both lists will be switched. This is done until the generation variable reaches 2.
You could add a depth parameter on the signature of your recursive method eg
on your main
recursiveCrawl(map,0);
and
public static void recursiveCrawl(Map<String, String> map, int depth) throws IOException {
if (depth++ < DESIRED_DEPTH) //assuming initial depth = 0
for (Map.Entry<String, String> entry : map.entrySet()) {
String key = entry.getKey();
Map<String, String> recurSive = returnURL(key);
recursiveCrawl(recurSive, depth);
}
}
]
You can do something like this:
static int maxLevels = 10;
public static void main(String args[]) throws IOException {
...
recursiveCrawl(map,0);
...
}
public static void recursiveCrawl(Map<String, String> map, int level) throws IOException {
for (Map.Entry<String, String> entry : map.entrySet()) {
String key = entry.getKey();
Map<String, String> recurSive = returnURL(key);
if (level < maxLevels) {
recursiveCrawl(recurSive, ++level);
}
}
}
Also, you can use a Set instead of a Map.
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()) {
...
}