I have written my own scanner to go through my JAX-RS resources and print out the method names and paths using jersey-server-1.18.1. The problem is when I migrate my same code to 2.16 (changing the package names from com.sun.* to org.glassfish.*), It just won't work.
Digging deep I found that those required jersey-server classes are no long public. Anyone knows the reason why? And how can I migrate my code below from 1.x to 2.x ? There is literally no documentation on this migration.
All help appreciated! Below is the code with 1.x
import com.wordnik.swagger.annotations.ApiOperation;
import com.sun.jersey.api.model.AbstractResource;
import com.sun.jersey.api.model.AbstractResourceMethod;
import com.sun.jersey.api.model.AbstractSubResourceLocator;
import com.sun.jersey.api.model.AbstractSubResourceMethod;
import com.sun.jersey.server.impl.modelapi.annotation.IntrospectionModeller;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author shivang
*/
public class Apiscanner {
public static void main(String[] args) {
Apiscanner runClass = new Apiscanner();
runClass.xyz();
}
public void xyz() {
AbstractResource resource = IntrospectionModeller.createResource(BaseResource.class);
String uriPrefix = resource.getPath().getValue();
abc(uriPrefix, resource);
}
public void abc(String uriPrefix, AbstractResource resource) {
for (AbstractResourceMethod srm : resource.getResourceMethods()) {
String uri = uriPrefix;
System.out.println(srm.getHttpMethod() + "\t" + uri);
}
for (AbstractSubResourceMethod srm : resource.getSubResourceMethods()) {
String uri = uriPrefix + srm.getPath().getValue();
ApiOperation op = srm.getAnnotation(ApiOperation.class);
System.out.println(srm.getHttpMethod() + "\t" + uri);
}
if (resource.getSubResourceLocators() != null && !resource.getSubResourceLocators().isEmpty()) {
for (AbstractSubResourceLocator subResourceLocator : resource.getSubResourceLocators()) {
ApiOperation op = subResourceLocator.getAnnotation(ApiOperation.class);
AbstractResource childResource = IntrospectionModeller.createResource(op.response());
String path = subResourceLocator.getPath().getValue();
String pathPrefix = uriPrefix + path;
abc(pathPrefix, childResource);
}
}
}
}
The new APIs for Jersey 2.x, can mainly be found in the org.glassfish.jersey.server.model package.
Some equivalents I can think of:
AbstractResource == Resource
IntrospectionModeller.createResource == I believe Resource.from(BaseResource.class)
AbstractResourceMethod == ResourceMethod
resource.getSubResourceMethods() == getChildResources(), which actually just returns a List<Resource>
AbstractSubResourceLocator == Doesn't seem to exist. We would simply check the above child resource to see if it is a locator
for (Resource childResource: resource.getChildResources()) {
if (childResource.getResourceLocator() != null) {
ResourceMethod method = childResource.getResourceLocator();
Class locatorType = method.getInvocable().getRawResponseType();
}
}
You can also use the enum ResourceMethod.JaxrsType.SUB_RESOURCE_LOCATOR to check if it equals the ResourceMethod.getType()
if (resourceMethod.getType()
.equals(ResourceMethod.JaxrsType.SUB_RESOURCE_LOCATOR) {
}
Here's what I was able to come up with, to kind of match what you got.
import com.wordnik.swagger.annotations.ApiOperation;
import org.glassfish.jersey.server.model.Resource;
import org.glassfish.jersey.server.model.ResourceMethod;
public class ApiScanner {
public static void main(String[] args) {
ApiScanner scanner = new ApiScanner();
scanner.xyz();
}
public void xyz() {
Resource resource = Resource.from(BaseResource.class);
abc(resource.getPath(), resource);
}
public void abc(String uriPrefix, Resource resource) {
for (ResourceMethod resourceMethod: resource.getResourceMethods()) {
String uri = uriPrefix;
System.out.println("-- Resource Method --");
System.out.println(resourceMethod.getHttpMethod() + "\t" + uri);
ApiOperation api = resourceMethod.getInvocable().getDefinitionMethod()
.getAnnotation(ApiOperation.class);
}
for (Resource childResource: resource.getChildResources()) {
System.out.println("-- Child Resource --");
System.out.println(childResource.getPath() + "\t" + childResource.getName());
if (childResource.getResourceLocator() != null) {
System.out.println("-- Sub-Resource Locator --");
ResourceMethod method = childResource.getResourceLocator();
Class locatorType = method.getInvocable().getRawResponseType();
System.out.println(locatorType);
Resource subResource = Resource.from(locatorType);
abc(childResource.getPath(), subResource);
}
}
}
}
OK. So I was able to get it to work almost at the same time as #peeskillet provided the answer. I will add just a different flavor of the answer in case people want to reuse the code:
import java.util.ArrayList;
import java.util.List;
import org.glassfish.jersey.server.model.Resource;
import org.glassfish.jersey.server.model.ResourceMethod;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author shivang
*/
public class JerseyResourceScanner {
public static void main(String[] args) {
JerseyResourceScanner runClass = new JerseyResourceScanner();
runClass.scan(BaseResource.class);
}
public void scan(Class baseClass) {
Resource resource = Resource.builder(baseClass).build();
String uriPrefix = "";
process(uriPrefix, resource);
}
private void process(String uriPrefix, Resource resource) {
String pathPrefix = uriPrefix;
List<Resource> resources = new ArrayList<>();
resources.addAll(resource.getChildResources());
if (resource.getPath() != null) {
pathPrefix = pathPrefix + resource.getPath();
}
for (ResourceMethod method : resource.getAllMethods()) {
if (method.getType().equals(ResourceMethod.JaxrsType.SUB_RESOURCE_LOCATOR)) {
resources.add(
Resource.from(resource.getResourceLocator()
.getInvocable().getDefinitionMethod().getReturnType()));
}
else {
System.out.println(method.getHttpMethod() + "\t" + pathPrefix);
}
}
for (Resource childResource : resources) {
process(pathPrefix, childResource);
}
}
}
Related
I have a sub-method that builds my FtpInboundFileSynchronizer object. (from a factory object generated out of scope)
private FtpInboundFileSynchronizer createFtpInboundFileSynchronizer(SessionFactory<FTPFile> factory) {
var synchronizer = new FtpInboundFileSynchronizer(factory);
CompositeFileListFilter filter = new CompositeFileListFilter<>();
filter.addFilter(new FtpSimplePatternFileListFilter("filename1.txt"));
filter.addFilter(new FtpSimplePatternFileListFilter("filename2.txt"));
synchronizer.setFilter(filter);
synchronizer.setRemoteDirectory(ftpConfiguration.getPath());
synchronizer.setDeleteRemoteFiles(false);
return synchronizer;
}
However, in this case, I get no files. If I remove one of the FTPSimplePAtternFileListFilter instances, it correctly retrieves that one filename from the FTP server.
The aim is to only download a predefined list of full file names, so both name and extension.
I cannot seem to wrap my head around how to do this. Anyone able to help?
import java.util.Arrays;
import org.apache.commons.net.ftp.FTPFile;
import org.springframework.integration.file.filters.AbstractDirectoryAwareFileListFilter;
import org.springframework.util.AntPathMatcher;
/**
* Filter to accept specific file name list.
*/
public class MultiPatternFileListFilter extends AbstractDirectoryAwareFileListFilter<FTPFile> {
private final AntPathMatcher matcher = new AntPathMatcher();
private String[] patterns;
public MultiPatternFileListFilter(String... patterns) {
this.patterns = patterns;
}
#Override
public boolean accept(FTPFile file) {
return alwaysAccept(file) || (file != null && this.matchesAnyPattern(file));
}
#Override
protected boolean isDirectory(FTPFile file) {
return false;
}
protected String getFilename(FTPFile file) {
return (file != null) ? file.getName() : null;
}
private boolean matchesAnyPattern(FTPFile file) {
return Arrays.stream(patterns).anyMatch(pattern -> this.matcher.match(pattern, this.getFilename(file)));
}
}
This solved my problem.
Is it possible to determine, what client libs have been loaded prior to a component?
We are running multiple site backed by different Javascript frameworks. In order to run a single component across the board, it's not sufficient to just use
<cq:includeClientLib categories="blah"/>
We need to identify the respective framework (i.e. AngularJS, Vanilla, jQuery, blah) in order to facilitate the integration.
We are looking for a decent server side solution.
I haven't actually done this, but it would presumably be possible if you are buffering your output to clone the JspWriter buffer or examine it to see what it already contains. That sounds ugly to me, though. But this is decompiled code for how the cq:includeClientLib tag adds libraries to the output, which may show you how you can read back what was previously written:
package com.adobe.granite.ui.tags;
import com.day.cq.widget.HtmlLibraryManager;
import java.io.IOException;
import javax.servlet.ServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.TagSupport;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.scripting.SlingBindings;
import org.apache.sling.scripting.jsp.util.TagUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class IncludeClientLibraryTag extends TagSupport {
private static final long serialVersionUID = -3068291967085012331L;
private static final Logger log = LoggerFactory.getLogger(IncludeClientLibraryTag.class);
private String categories;
private String js;
private String css;
private String theme;
private Boolean themed;
public IncludeClientLibraryTag() {
}
public void setPageContext(PageContext pageContext) {
super.setPageContext(pageContext);
this.categories = null;
this.js = null;
this.css = null;
this.theme = null;
this.themed = null;
}
public void setCategories(String categories) {
this.categories = categories;
}
public void setJs(String js) {
this.js = js;
}
public void setCss(String css) {
this.css = css;
}
public void setTheme(String theme) {
this.theme = theme;
}
public void setThemed(boolean themed) {
this.themed = Boolean.valueOf(themed);
}
public int doEndTag() throws JspException {
SlingHttpServletRequest request = TagUtil.getRequest(this.pageContext);
HtmlLibraryManager libManager = this.getHtmlLibraryManager(request);
if(libManager == null) {
log.warn("<ui:includeClientLib>: Could not retrieve HtmlLibraryManager service, skipping inclusion.");
return 6;
} else {
JspWriter out = this.pageContext.getOut();
try {
if(this.categories != null) {
libManager.writeIncludes(request, out, toArray(this.categories));
} else if(this.theme != null) {
libManager.writeThemeInclude(request, out, toArray(this.theme));
} else if(this.js != null) {
if(this.themed != null) {
libManager.writeJsInclude(request, out, this.themed.booleanValue(), toArray(this.js));
} else {
libManager.writeJsInclude(request, out, toArray(this.js));
}
} else if(this.css != null) {
if(this.themed != null) {
libManager.writeCssInclude(request, out, this.themed.booleanValue(), toArray(this.css));
} else {
libManager.writeCssInclude(request, out, toArray(this.css));
}
}
return 6;
} catch (IOException var6) {
String libs = this.categories != null?"categories: " + this.categories:(this.theme != null?"theme: " + this.theme:(this.js != null?"js: " + this.js:(this.css != null?"css: " + this.css:"")));
throw new JspException("Could not include client library: " + libs, var6);
}
}
}
private HtmlLibraryManager getHtmlLibraryManager(ServletRequest request) {
SlingBindings bindings = (SlingBindings)request.getAttribute(SlingBindings.class.getName());
return (HtmlLibraryManager)bindings.getSling().getService(HtmlLibraryManager.class);
}
private static String[] toArray(String commaSeparatedList) {
if(commaSeparatedList == null) {
return new String[0];
} else {
String[] split = commaSeparatedList.split(",");
for(int i = 0; i < split.length; ++i) {
split[i] = split[i].trim();
}
return split;
}
}
}
I think the best solution may be to use the client library dependencies or embed attributes in your library, though, or let the client-side JavaScript test if a library is present (ex. test if the jQuery object is undefined) and then take appropriate action. In other words, let the client side determine the final rendering based on what libraries exist on in the client. It sounds like this may not be possible for your situation, though.
dependencies: This is a list of other client library categories on
which this library folder depends. For example, given two
cq:ClientLibraryFolder nodes F and G, if a file in F requires another
file in G in order to function properly, then at least one of the
categories of G should be among the dependencies of F.
embed: Used to > embed code from other libraries. If node F embeds nodes G and H, the
resulting HTML will be a concetration of content from nodes G and H.
I've one .DRL file which has say 10 rules. Once I insert a fact, some rules may be matched- how do I find out which rules were matched programmatically?
Note that this answer is valid for versions of Drools up to 5.x. If you have moved on to 6 or above, then take a look at the modified answer from #melchoir55. I haven't tested it myself, but I'll trust that it works.
To keep track of rule activations, you can use an AgendaEventListener. Below is an example, as found here:
https://github.com/gratiartis/sctrcd-payment-validation-web/blob/master/src/main/java/com/sctrcd/drools/util/TrackingAgendaEventListener.java
You just need to create such a listener and attach it to the session like so:
ksession = kbase.newStatefulKnowledgeSession();
AgendaEventListener agendaEventListener = new TrackingAgendaEventListener();
ksession.addEventListener(agendaEventListener);
//...
ksession.fireAllRules();
//...
List<Activation> activations = agendaEventListener.getActivationList();
Note that there is also WorkingMemoryEventListener which enables you to do the same with tracking insertions, updates and retractions of facts.
Code for a tracking & logging AgendaEventListener:
package com.sctrcd.drools.util;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.drools.definition.rule.Rule;
import org.drools.event.rule.DefaultAgendaEventListener;
import org.drools.event.rule.AfterActivationFiredEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A listener that will track all rule firings in a session.
*
* #author Stephen Masters
*/
public class TrackingAgendaEventListener extends DefaultAgendaEventListener {
private static Logger log = LoggerFactory.getLogger(TrackingAgendaEventListener.class);
private List<Activation> activationList = new ArrayList<Activation>();
#Override
public void afterActivationFired(AfterActivationFiredEvent event) {
Rule rule = event.getActivation().getRule();
String ruleName = rule.getName();
Map<String, Object> ruleMetaDataMap = rule.getMetaData();
activationList.add(new Activation(ruleName));
StringBuilder sb = new StringBuilder("Rule fired: " + ruleName);
if (ruleMetaDataMap.size() > 0) {
sb.append("\n With [" + ruleMetaDataMap.size() + "] meta-data:");
for (String key : ruleMetaDataMap.keySet()) {
sb.append("\n key=" + key + ", value="
+ ruleMetaDataMap.get(key));
}
}
log.debug(sb.toString());
}
public boolean isRuleFired(String ruleName) {
for (Activation a : activationList) {
if (a.getRuleName().equals(ruleName)) {
return true;
}
}
return false;
}
public void reset() {
activationList.clear();
}
public final List<Activation> getActivationList() {
return activationList;
}
public String activationsToString() {
if (activationList.size() == 0) {
return "No activations occurred.";
} else {
StringBuilder sb = new StringBuilder("Activations: ");
for (Activation activation : activationList) {
sb.append("\n rule: ").append(activation.getRuleName());
}
return sb.toString();
}
}
}
Steve's answer is solid, but the major changes brought in drools 6 make the code obsolete. I am posting below a rewrite of Steve's code which takes into account the new api:
package your.preferred.package;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.drools.core.event.DefaultAgendaEventListener;
import org.kie.api.definition.rule.Rule;
import org.kie.api.event.rule.AfterMatchFiredEvent;
import org.kie.api.runtime.rule.Match;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A listener that will track all rule firings in a session.
*
* #author Stephen Masters, Isaac Martin
*/
public class TrackingAgendaEventListener extends DefaultAgendaEventListener {
private static Logger log = LoggerFactory.getLogger(TrackingAgendaEventListener.class);
private List<Match> matchList = new ArrayList<Match>();
#Override
public void afterMatchFired(AfterMatchFiredEvent event) {
Rule rule = event.getMatch().getRule();
String ruleName = rule.getName();
Map<String, Object> ruleMetaDataMap = rule.getMetaData();
matchList.add(event.getMatch());
StringBuilder sb = new StringBuilder("Rule fired: " + ruleName);
if (ruleMetaDataMap.size() > 0) {
sb.append("\n With [" + ruleMetaDataMap.size() + "] meta-data:");
for (String key : ruleMetaDataMap.keySet()) {
sb.append("\n key=" + key + ", value="
+ ruleMetaDataMap.get(key));
}
}
log.debug(sb.toString());
}
public boolean isRuleFired(String ruleName) {
for (Match a : matchList) {
if (a.getRule().getName().equals(ruleName)) {
return true;
}
}
return false;
}
public void reset() {
matchList.clear();
}
public final List<Match> getMatchList() {
return matchList;
}
public String matchsToString() {
if (matchList.size() == 0) {
return "No matchs occurred.";
} else {
StringBuilder sb = new StringBuilder("Matchs: ");
for (Match match : matchList) {
sb.append("\n rule: ").append(match.getRule().getName());
}
return sb.toString();
}
}
}
You can use a static logger factory which will log with your favorite logger the actions from your DRL file.
For instance:
import org.drools.runtime.rule.RuleContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public final class DRLLogger {
private DRLLogger() {
}
protected static Logger getLogger(final RuleContext drools) {
final String category = drools.getRule().getPackageName() + "." + drools.getRule().getName();
final Logger logger = LoggerFactory.getLogger(category);
return logger;
}
public static void info(final RuleContext drools, final String message, final Object... parameters) {
final Logger logger = getLogger(drools);
logger.info(message, parameters);
}
public static void debug(final RuleContext drools, final String message, final Object... parameters) {
final Logger logger = getLogger(drools);
logger.debug(message, parameters);
}
public static void error(final RuleContext drools, final String message, final Object... parameters) {
final Logger logger = getLogger(drools);
logger.error(message, parameters);
}
}
Then from your DRL file:
import function com.mycompany.DRLLogger.*
rule "myrule"
when
$fact: Fact()
then
info(drools, "Fact:{}", $fact);
end
Change the dialect to JAVA in DRL file.
Insert a HashMap from the java file to DRL file (using Drools session concept),
which should contain the rule name as key and boolean value as result.
Follow this link to know how to insert Map to the DRL file.
You can now find which rule exactly matched.
Hope this helps :)
You can print info about rule executed from DRL file itself using RuleContext:drools
System.out.println(drools.getRule().getName())
i'd like to implement a index on a custom asset made for my project called "projet", i've already developped this class : (based on the liferay's bookmark indexer )
/**
* Copyright (c) 2000-2012 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Locale;
import javax.portlet.PortletURL;
import org.apache.log4j.Logger;
import com.liferay.portal.kernel.search.BaseIndexer;
import com.liferay.portal.kernel.search.BooleanQuery;
import com.liferay.portal.kernel.search.Document;
import com.liferay.portal.kernel.search.Field;
import com.liferay.portal.kernel.search.Indexer;
import com.liferay.portal.kernel.search.SearchContext;
import com.liferay.portal.kernel.search.SearchEngineUtil;
import com.liferay.portal.kernel.search.Summary;
import com.liferay.portal.kernel.util.GetterUtil;
import com.liferay.portal.model.Group;
import com.liferay.portal.service.ClassNameLocalServiceUtil;
import com.liferay.portal.service.GroupLocalServiceUtil;
import com.liferay.portal.util.PortletKeys;
public class ProjetIndexer extends BaseIndexer {
private static Logger LOGGER = Logger.getLogger(ProjetIndexer.class);
public static final String[] CLASS_NAMES = { Projet.class.getName() };
public String[] getClassNames() {
return CLASS_NAMES;
}
public String getPortletId() {
return Long.toString(ClassNameLocalServiceUtil.getClassNameId(Projet.class)) ;
}
#Override
protected void doDelete(Object obj) throws Exception {
LOGGER.info("doDelete");
Projet entry = (Projet) obj;
deleteDocument(entry.getCompanyId(), entry.getPrimaryKey());
}
#Override
protected Document doGetDocument(Object obj) throws Exception {
LOGGER.info("doGetDocument");
Projet entry = (Projet) obj;
Document document = getBaseModelDocument(getPortletId(), entry);
document.addText(Field.DESCRIPTION, "test123");
document.addText(Field.TITLE, "test123");
document.addKeyword(Field.TYPE, entry.getType());
document.addKeyword(Field.COMPANY_ID, entry.getCompanyId());
//what else ??
return document;
}
#Override
protected Summary doGetSummary(Document document, Locale locale,
String snippet, PortletURL portletURL) throws Exception {
LOGGER.info("doGetSummary");
String title = document.get(Field.TITLE);
String url = document.get(Field.URL);
String entryId = document.get(Field.ENTRY_CLASS_PK);
// portletURL.setParameter("struts_action",
// "/bookmarks/view_entry");TODO
portletURL.setParameter("entryId", entryId);
return new Summary(title, url, portletURL);
}
#Override
protected void doReindex(Object obj) throws Exception {
LOGGER.info("doReindex");
Projet entry = (Projet) obj;
Document document = getDocument(entry);
SearchEngineUtil.updateDocument(entry.getCompanyId(), document);
}
#Override
protected void doReindex(String className, long classPK) throws Exception {
LOGGER.info("doReindex");
Projet entry = ProjetLocalServiceUtil.getProjet(classPK);
doReindex(entry);
}
#Override
protected void doReindex(String[] ids) throws Exception {
long companyId = GetterUtil.getLong(ids[0]);
LOGGER.info("doReindex");
// reindexFolders(companyId);
reindexRoot(companyId);
}
#Override
protected String getPortletId(SearchContext searchContext) {
return getPortletId();
}
protected void reindexRoot(long companyId) throws Exception {
LOGGER.info("reindexRoot");
int groupCount = GroupLocalServiceUtil.getCompanyGroupsCount(companyId);
int groupPages = groupCount / Indexer.DEFAULT_INTERVAL;
for (int i = 0; i <= groupPages; i++) {
int groupStart = (i * Indexer.DEFAULT_INTERVAL);
int groupEnd = groupStart + Indexer.DEFAULT_INTERVAL;
reindexRoot(companyId, groupStart, groupEnd);
}
}
protected void reindexRoot(long companyId, int groupStart, int groupEnd)
throws Exception {
LOGGER.info("reindexRoot");
List<Group> groups = GroupLocalServiceUtil.getCompanyGroups(companyId,
groupStart, groupEnd);
for (Group group : groups) {
long groupId = group.getGroupId();
// long folderId =
// BookmarksFolderConstants.DEFAULT_PARENT_FOLDER_ID;
int entryCount = ProjetLocalServiceUtil.getEntriesCount(groupId);
int entryPages = entryCount / Indexer.DEFAULT_INTERVAL;
for (int i = 0; i <= entryPages; i++) {
int entryStart = (i * Indexer.DEFAULT_INTERVAL);
int entryEnd = entryStart + Indexer.DEFAULT_INTERVAL;
reindexEntries(companyId, groupId, entryStart, entryEnd);
}
}
}
protected void reindexEntries(long companyId, long groupId, int entryStart,
int entryEnd) throws Exception {
LOGGER.info("reindexEntries");
List<Projet> entries = ProjetLocalServiceUtil.getEntries(groupId,
entryStart, entryEnd);
if (entries.isEmpty()) {
return;
}
Collection<Document> documents = new ArrayList<Document>();
for (Projet entry : entries) {
Document document = getDocument(entry);
documents.add(document);
}
SearchEngineUtil.updateDocuments(companyId, documents);
}
}
and this is my liferay portlet.xml:
<indexer-class>path package .ProjetIndexer</indexer-class>
but it doesnt work. search portlet (bundled with liferay 6.0) does not retrieve my custom asset
any ideas? thank
My issue is solved by deleting data under /data/lucent/ Maybe my tests deleloppment was corrupted I've changed the method doGetDocument too, making sure that no empty field is set in the map. many thanks for your cooperation
I'm writing a wicket project for a social network.In my project i have authentication so when a user enter address of the home page he is redirected to login page in this way:
public class MyApplication extends WebApplication {
private Folder uploadFolder = null;
#Override
public Class getHomePage() {
return UserHome.class;
}
public Folder getUploadFolder()
{
return uploadFolder;
}
#Override
protected void init() {
super.init();
// Disable the Ajax debug label!
//getDebugSettings().setAjaxDebugModeEnabled(false);
this.getMarkupSettings().setDefaultMarkupEncoding("UTF-8");
this.getRequestCycleSettings().setResponseRequestEncoding("UTF-8");
mountBookmarkablePage("/BossPage", BossPage.class);
mountBookmarkablePage("/Branch", EditProfile.class);
mountBookmarkablePage("/SA", SuperAdmin.class);
mountBookmarkablePage("/Admin", ir.pnusn.branch.ui.pages.administratorPages.EditProfile.class);
mountBookmarkablePage("/Student", StudentSignUP.class);
mountBookmarkablePage("/Student/Test", StudentSignUpConfirm.class);
mountBookmarkablePage("/Branch/categories.xml", CategoriesXML.class);
get().getPageSettings().setAutomaticMultiWindowSupport(true);
getResourceSettings().setThrowExceptionOnMissingResource(false);
uploadFolder = new Folder("C:\\", "wicket-uploads");
uploadFolder.mkdirs();
this.getSecuritySettings().setAuthorizationStrategy(WiaAuthorizationStrategy.getInstance());
this.getSecuritySettings().setUnauthorizedComponentInstantiationListener(WiaAuthorizationStrategy.getInstance());
addComponentInstantiationListener(new IComponentInstantiationListener() {
public void onInstantiation(final Component component) {
if (!getSecuritySettings().getAuthorizationStrategy().isInstantiationAuthorized(component.getClass())) {
try {
getSecuritySettings().getUnauthorizedComponentInstantiationListener().onUnauthorizedInstantiation(component);
} catch (Exception e) {
System.out.println("ERRORRRRRRR:" + e.toString());
}
}
}
});
}
}
and my WiaAuthorizationStrategy class is like this which will get page names and user roles from a xml file by name Realm.xml :
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package ir.pnusn.ui.library;
import ir.pnusn.authentication.RealmPolicy;
import ir.pnusn.authentication.ui.pages.Login;
import org.apache.wicket.Component;
import org.apache.wicket.RestartResponseAtInterceptPageException;
import org.apache.wicket.authorization.Action;
import org.apache.wicket.authorization.IAuthorizationStrategy;
import org.apache.wicket.authorization.IUnauthorizedComponentInstantiationListener;
public final class WiaAuthorizationStrategy implements
IAuthorizationStrategy,
IUnauthorizedComponentInstantiationListener {
private RealmPolicy roleManager;
private static WiaAuthorizationStrategy instance;
private WiaAuthorizationStrategy() {
roleManager = RealmPolicy.getInstance();
}
public static WiaAuthorizationStrategy getInstance() {
if(instance == null)
instance = new WiaAuthorizationStrategy();
return instance;
}
public boolean isInstantiationAuthorized(Class componentClass) {
if (ProtectedPage.class.isAssignableFrom(componentClass)) {
if (WiaSession.get().getUser() == null) {
return false;
}
if(!roleManager.isAuthorized(WiaSession.get().getUser().getRole(), componentClass.getName()))//WiaSession.get().isAuthenticated();
{
WiaSession.get().setAccess(false);
return false;
}
else
return true;
}
return true;
}
public void onUnauthorizedInstantiation(Component component) {
throw new RestartResponseAtInterceptPageException(
Login.class);
}
public boolean isActionAuthorized(Component component, Action action) {
//System.out.println("Name:" + component.getClass().getName() + "\n Action:" + action.getName() + "\nUser:" + WiaSession.get().getUser());
if (action.equals(Component.RENDER)) {
if (roleManager.containClass(component.getClass().getName()))
{
if (WiaSession.get().getUser() != null) {
if(!roleManager.isAuthorized(WiaSession.get().getUser().getRole(), component.getClass().getName()))
{
WiaSession.get().setAccess(false);
return false;
}
return true;
}
return false;
}
}
return true;
}
}
in this situation i have a googlemap in one of my protectedpage and because googlemap needs to read data for loading builing from a xml so i create a servlet which will create it dynamicly depending on the Username. this servlet is below:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package ir.pnusn.branch.ui.pages;
import ir.pnusn.branch.database.BranchNotFoundException;
import ir.pnusn.branch.database.DatabaseException;
import ir.pnusn.branch.facade.admin.branchDataEnter.BranchDataSubmitFacade;
import ir.pnusn.branch.facade.admin.branchDataEnter.BuildingBean;
import java.util.Iterator;
import java.util.List;
import org.apache.wicket.PageParameters;
import org.apache.wicket.RequestCycle;
import org.apache.wicket.markup.html.WebPage;
/**
*
* #author mohammad
*/
public class CategoriesXML extends WebPage
{
public CategoriesXML(PageParameters parameters)
{
System.out.println("user " + parameters.getString("user"));
StringBuilder builder = new StringBuilder("<markers>");
List<BuildingBean> buildings;
try
{
buildings = BranchDataSubmitFacade.createBranchDataSubmitFacade(parameters.getString("user")).getBranchSecondPageData();
for (Iterator<BuildingBean> it = buildings.iterator(); it.hasNext();)
{
BuildingBean buildingBean = it.next();
builder.append("<marker lat=\"");
builder.append(buildingBean.getLatit());
builder.append("\" lng=\"");
builder.append(buildingBean.getLongit());
builder.append("\"");
builder.append(" address=\"");
builder.append(buildingBean.getDesctiption());
builder.append("\" category=\"branch\" name=\"");
builder.append(buildingBean.getBuildingName());
builder.append("\"/>");
}
builder.append("</markers>");
}
catch (DatabaseException ex)
{
builder = new StringBuilder("<markers></markers>");
}
catch (BranchNotFoundException ex)
{
builder = new StringBuilder("<markers></markers>");
}
RequestCycle.get().getResponse().println(builder.toString());
/*"<markers>" +
"<marker lat=\"35.69187\" lng=\"51.413269\" address=\"Some stuff to display in the First Info Window\" category=\"branch\" name=\"gholi\"/>" +
"<marker lat=\"52.91892\" lng=\"78.89231\" address=\"Some stuff to display in the Second Info Window\" category=\"branch\" name=\"taghi\"/>" +
"<marker lat=\"40.82589\" lng=\"35.10040\" address=\"Some stuff to display in the Third Info Window\" category=\"branch\" name=\"naghi\"/>" +
"</markers> "**/
}
}
I have made this page at first protected and so the user had to loged in to have access this xml but after lot's of debuging i found that googlemap can't log in my system so instead of parsing the dataxml it pars login page html az input. so i changed the extention of the CategoriesXML to extend WebPage.
But now I have another problem:
When i go to the google map page in my Social site I can Not refresh the page because It expires and so I cannot add another building to my data xml.
what should I do?
tell me if you need more code or information
In trying to close this question, which the OP seems to have pretty much abandoned, I'll just post my old comment as an answer..:
In your CategoriesXML I would highly advise against building and adding your tags as Strings and adding them to pages just like that. See if you can work this into a in your .xml(?) file instead, as that's the Wicket way to do things (and as such just might solve the problems you're having)
Would making this WebPage extends org.apache.wicket.Page instead and associate the markup to return as xml instead of html? Basically, mimicking a WebPage, but implementing it for XML.