Jira SAL using PluginSettings - plugins

I looked for a way to store project-specific configurations for my plugin.
In the first step i only want to store a simple String like "Hello".
So, what i found is SAL and the PluginSettings.
https://developer.atlassian.com/docs/atlassian-platform-common-components/shared-access-layer/sal-services
This seems pretty easy to use but I don´t have any idea how to implement it into my code.
I used a WebWork taking place in the project administration section:
#Override
public String doDefault() throws Exception {
Project project = getProjectManager().getProjectObjByKey(_projectKey);
HttpServletRequest request = ExecutingHttpRequest.get();
request.setAttribute((new StringBuilder()).append("com.atlassian.jira.projectconfig.util.ServletRequestProjectConfigRequestCache").append(":project").toString(), project);
return INPUT;
}
#Override
protected String doExecute() throws Exception {
Project project = getProjectManager().getProjectObjByKey(_projectKey);
HttpServletRequest request = ExecutingHttpRequest.get();
request.setAttribute((new StringBuilder()).append("com.atlassian.jira.projectconfig.util.ServletRequestProjectConfigRequestCache").append(":project").toString(), project);
String param = request.getParameter("param");
return SUCCESS;
}
public void setProjectKey(String projectKey) {
_projectKey = projectKey;
}
public String getProjectKey() {
return _projectKey;
}
public String getBaseUrl() {
return ComponentAccessor.getApplicationProperties().getString(APKeys.JIRA_BASEURL);
}
As SAL said i implemented a Settings-Class:
public CustomProjectSettings(
final PluginSettingsFactory pluginSettingsFactory,
final String projectKey) {
this.pluginSettingsFactory = pluginSettingsFactory;
this.projectKey = projectKey;
}
public void setValue(final String key, final String value) {
final PluginSettings settings = pluginSettingsFactory
.createSettingsForKey(projectKey);
settings.put(key, value);
}
public Object getValue(final String key) {
final PluginSettings settings = pluginSettingsFactory
.createSettingsForKey(projectKey);
return settings.get(key);
}
And I added the component in the xml:
<component-import key="pluginSettingsFactory" interface="com.atlassian.sal.api.pluginsettings.PluginSettingsFactory" />
So how do i connect and implement this into my webwork to say
protected String doExecute() throws Exception{
[...]
pluginSettings.setValue("Key", param);
[...]
}

It was easier than i thought.
I simply had to inject the Settings as a dependency for my WebWork:
public WebWorkAction(CustomProjectSettings settings){
this.settings = settings
}
The Settings-Class gets autowired by
<component-import key="pluginSettingsFactory"
interface="com.atlassian.sal.api.pluginsettings.PluginSettingsFactory" />
and by adding
<component key="settingsComponent"
class="com.xxx.CustomProjectSettings">
</component>

Related

JsonpRequestBuilder with typed response throws InCompatibleClassChangeError

I have an existing app that I'm adding a "Suggested Products" feature to and I'm having trouble with my JSONP response not being properly transformed to the typed JsArray. I'm hoping someone can give me an idea of what I'm doing wrong?
I have defined my type that will be returned from the server in its own class:
import com.google.gwt.core.client.JavaScriptObject;
public class SuggestedProduct extends JavaScriptObject {
protected SuggestedProduct() {}
public final native String getFormName();
public final native String getImageURL();
}
I have a method that uses the JsonpRequestBuilder to fire off a request to get my JSON.
private void loadSuggestedProducts() {
JsonpRequestBuilder builder = new JsonpRequestBuilder();
builder.requestObject(buildSuggestedProductURL(), new AsyncCallback<JsArray<SuggestedProduct>>() {
public void onFailure(Throwable caught) {
//Handle errors
}
public void onSuccess(JsArray<SuggestedProduct> data) {
if ( data == null) {
//Handle empty data
return;
}
SafeHtmlBuilder sb = new SafeHtmlBuilder();
sb.appendHtmlConstant("<h4>Suggested Products:</h4>");
for (int i=0; i < data.length(); i++) {
SuggestedProduct product = data.get(i); //<- This line throws the exception
sb.appendHtmlConstant("<div class=\"card\">");
sb.appendHtmlConstant("<img class=\"card-img-top\" src=\"" + product.getImageURL() + "\" alt=\"" + product.getFormName() + "\">");
sb.appendHtmlConstant("<div class=\"card-body\">");
sb.appendHtmlConstant("<h5 class=\"card-title\">" + product.getFormName() + "</h5>");
sb.appendHtmlConstant("<a onclick=\"javascript:addItems();\" class=\"cmd-add\">Add <i aria-hidden=\"true\" class=\"fa fa-plus-circle\"></i></a>");
sb.appendHtmlConstant("</div></div>");
}
view.getSuggestedProducts().setInnerSafeHtml(sb.toSafeHtml());
}
});
}
When I try to use a SuggestedProduct from the response, I get an error:
java.lang.IncompatibleClassChangeError: Found interface
com.google.gwt.cor.client.JsArray, but class was expected
I've been following the guide in the GWT documentation. I don't see any difference between what I'm trying and what they say will work. When I debug, it looks as though the returned data is an array of SuggestedProducts, so I'm stumped as to how to proceed. Any help would be appreciated.
After closer inspection I realized my overlay type was missing method bodies for what fields to return from the JSON object they represented. The fix was to include the proper JSNI method definitions.
import com.google.gwt.core.client.JavaScriptObject;
public class SuggestedProduct extends JavaScriptObject {
protected SuggestedProduct() {}
public final native String getFormName() /*-{ return this.formname; }-*/;
public final native String getImageURL() /*-{ return this.imageurl; }-*/;
}

E4 Preference Initializer won´t get called

I´m trying to migrate my e3-rcp-app to a e4-rcp-app.
Therefore I need to define my default Preferences. (Not the Pref.Pages)
And by doing and trying so, I just can´t get my Initializer called. Here Is my initializer-class:
public class MyPreferenceInitializer extends AbstractPreferenceInitializer {
public MyPreferenceInitializer (){}
#Override
public void initializeDefaultPreferences() {
Preferences defaults = DefaultScope.INSTANCE.getNode(InspectIT.ID);
// Set defaults using things like:
defaults.put("DUMMY", "DUMMYCONTENT");
try {
defaults.flush();
} catch (BackingStoreException e) {
e.printStackTrace();
}
//And this other approach to make sure that one of them works
IPreferenceStore store = InspectIT.getDefault().getPreferenceStore();
store.setDefault("DUMMY", "DUMMYCONTENT");
try {
((Preferences) store).flush();
} catch (BackingStoreException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//Dummy impl
default Preferences....,
}
}
I also got an Activator class with the following structure: (Just posting the relevant methods(?))
public class Activator implements BundleActivator {
private static BundleContext context;
static BundleContext getContext() {
return context;
}
private static Activator plugin;
private volatile ScopedPreferenceStore preferenceStore;
public void start(BundleContext context) throws Exception {
plugin = this;
Activator.context = context;
locateRuntimeDir();
logListener = new LogListener();
Platform.addLogListener(logListener);
//access to my initializor
String text = getPreferenceStore().getDefaultString("DUMMY");
String text2 = getPreferenceStore().getString("DUMMY");
}
public void stop(BundleContext context) throws Exception {
Activator.context = null;
plugin = null;
}
public static <E> E getService(Class<E> clazz) {
ServiceReference<E> reference = context.getServiceReference(clazz);
if (null != reference) {
return context.getService(reference);
}
throw new RuntimeException("Requested service of the class " + clazz.getName() + " is not registered in the bundle.");
}
public ScopedPreferenceStore getPreferenceStore() {
if (null == preferenceStore) {
synchronized (this) {
if (null == preferenceStore) {
preferenceStore = new ScopedPreferenceStore(ConfigurationScope.INSTANCE, ID);
}
}
}
return preferenceStore;
}
}
The ScopedPreferenceStore I´m using is the one available at: https://github.com/opcoach/e4Preferences/tree/master/com.opcoach.e4.preferences
As well, I declared the plugin.xml Extension like this (I do need this, right?)
...
<extension
point="org.eclipse.core.runtime.preferences">
<initializer class="MyApplication.rcp.preferences.MyPreferenceInitializer ">
</initializer>
</extension>
...
I´m using Eclipse 4.5.1 on a win7 x64
I googled a lot and found a lot of Threads concerning this, but I just can´t find my mistake =/.
Anyone got a suggestion for why my default preferences initializer won´t get called?
Thanks in advance
You must still use the org.eclipse.core.runtime.preferences extension point to define the preferences initializer.
<extension
point="org.eclipse.core.runtime.preferences">
<initializer
class="package.MyPreferenceInitializer">
</initializer>
</extension>
In the initializer use:
#Override
public void initializeDefaultPreferences()
{
Preferences defaults = DefaultScope.INSTANCE.getNode(Activator.ID);
// Set defaults using things like:
defaults.putInt("pref id", 0);
}
Finally I found a solution for this issue.
Accidentally got over this problem again and the mistake was in the Activator. I wrongly set the ID onto a wrong name. I reset it to my projects name and now it is working!
public ScopedPreferenceStore getPreferenceStore() {
if (null == preferenceStore) {
synchronized (this) {
if (null == preferenceStore)
preferenceStore = new ScopedPreferenceStore(ConfigurationScope.INSTANCE, ID);
}
}
return preferenceStore;
}
ID = Project-Name

Get and Set attribute values of a class using aspectJ

I am using aspectj to add some field to a existing class and annotate it also.
I am using load time weaving .
Example :- I have a Class customer in which i am adding 3 string attributes. But my issues is that I have to set some values and get it also before my business call.
I am trying the below approach.
In my aj file i have added the below, my problem is in the Around pointcut , how do i get the attribute and set the attribute.
public String net.customers.PersonCustomer.getOfflineRiskCategory() {
return OfflineRiskCategory;
}
public void net.customers.PersonCustomer.setOfflineRiskCategory(String offlineRiskCategory) {
OfflineRiskCategory = offlineRiskCategory;
}
public String net.customers.PersonCustomer.getOnlineRiskCategory() {
return OnlineRiskCategory;
}
public void net.customers.PersonCustomer.setOnlineRiskCategory(String onlineRiskCategory) {
OnlineRiskCategory = onlineRiskCategory;
}
public String net.customers.PersonCustomer.getPersonCommercialStatus() {
return PersonCommercialStatus;
}
public void net.customers.PersonCustomer.setPersonCommercialStatus(String personCommercialStatus) {
PersonCommercialStatus = personCommercialStatus;
}
#Around("execution(* net.xxx.xxx.xxx.DataMigration.populateMap(..))")
public Object invoke(ProceedingJoinPoint joinPoint) throws Throwable {
Object arguments[] = joinPoint.getArgs();
if (arguments != null) {
HashMap<String, String> hMap = (HashMap) arguments[0];
PersonCustomer cus = (PersonCustomer) arguments[1];
return joinPoint.proceed();
}
If anyone has ideas please let me know.
regards,
FT
First suggestion, I would avoid mixing code-style aspectj with annotation-style. Ie- instead of #Around, use around.
Second, instead of getting the arguments from the joinPoint, you should bind them in the pointcut:
Object around(Map map, PersonCustomer cust) :
execution(* net.xxx.xxx.xxx.DataMigration.populateMap(Map, PersonCustomer) && args(map, cust) {
...
return proceed(map, cust);
}
Now, to answer your question: you also need to use intertype declarations to add new fields to your class, so do something like this:
private String net.customers.PersonCustomer.OfflineRiskCategory;
private String net.customers.PersonCustomer.OnlineRiskCategory;
private String net.customers.PersonCustomer.PersonCommercialStatus;
Note that the private keyword here means private to the aspect, not to the class that you declare it on.

How to redirect to an anchor in JSF?

Let's say I have this action in a JSF Managed Bean:
public String doSomething() {
FacesContext.getCurrentInstance().getExternalContext().getFlash().put("msg", "Something was done successfully");
return "view?faces-redirect=true";
}
My view has an anchor element with the id msg. I want the url to have this anchor (for accessibility matters), like:
view.jsf#msg
Or whatever is my FacesServlet filter pattern.
return "view#msg?faces-redirect=true"; obviously will not work because JSF (mojarra at least) will try to evaluate view#msg as a view.
So my question is how to make JSF redirect to a URL with #msg in the end.
because JSF (mojarra at least) will try to evaluate view#msg as a view
Oh, that's nasty. It's definitely worth an enhancement request at the JSF/Mojarra boys.
Your best bet is to send the redirect manually with help of ExternalContext#redirect().
public void doSomething() throws IOException {
ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
ec.getFlash().put("msg", "Something was done successfully");
ec.redirect("view.xhtml#msg");
}
(assuming that FacesServlet is mapped on *.xhtml)
Alternatively, you could conditionally render a piece of JS which does that instead.
<ui:fragment rendered="#{not empty flash.msg}">
<script>window.location.hash = 'msg';</script>
</ui:fragment>
You try to build an illegal URL - the fragment (#) is always the last part of an URL.
return "view?faces-redirect=true#msg" would be the correct URL.
Unfortunately that fragment is stripped by the default NavigationHandler, at least in JSF 2.2.
While the two options of BalusC are working as well, I have a third option to offer. Wrap the NavigationHandler and ViewHandler with a small patch:
public class MyViewHandler extends ViewHandlerWrapper {
public static final String REDIRECT_FRAGMENT_ATTRIBUTE = MyViewHandler.class.getSimpleName() + ".redirect.fragment";
// ... Constructor and getter snipped ...
public String getRedirectURL(final FacesContext context, final String viewId, final Map<String, List<String>> parameters, final boolean includeViewParams) {
final String redirectURL = super.getRedirectURL(context, viewId, removeNulls(parameters), includeViewParams);
final Object fragment = context.getAttributes().get(REDIRECT_FRAGMENT_ATTRIBUTE);
return fragment == null ? redirectURL : redirectURL + fragment;
}
}
public class MyNavigationHandler extends ConfigurableNavigationHandlerWrapper {
// ... Constructor and getter snipped ...
public void handleNavigation(final FacesContext context, final String fromAction, final String outcome) {
super.handleNavigation(context, fromAction,
storeFragment(context, outcome));
}
public void handleNavigation(final FacesContext context, final String fromAction, final String outcome, final String toFlowDocumentId) {
super.handleNavigation(context, fromAction,
storeFragment(context, outcome), toFlowDocumentId);
}
private static String storeFragment(final FacesContext context, final String outcome) {
if (outcome != null) {
final int hash = outcome.lastIndexOf('#');
if (hash >= 0 && hash + 1 < outcome.length() && outcome.charAt(hash + 1) != '{') {
context.getAttributes().put(MyViewHandler.REDIRECT_FRAGMENT_ATTRIBUTE, outcome.substring(hash));
return outcome.substring(0, hash);
}
}
return outcome;
}
}
(I had to create the wrapper for the ViewHandler anyway, because of a fix for JAVASERVERFACES-3154)

SuggestBox override addSelectionHandler

I have a custom Oracle with Objects to pass to the SuggestBox. Then I need get back a object when it's selected from de SuggestBox.
public HandlerRegistration addSelectionHandler(SelectionHandler<SuggestOracle.Suggestion> handler)
The problem is that I don't have Suggestion. I have "CustomSuggestion". I read de API and I try to write a Custom SuggestBox implementing the interface HasSelectionHandlers but I can't because the SuggestBox have a implementation of the interface. I get the error:
The interface HasSelectionHandlers cannot be implemented more than once with different arguments: HasSelectionHandlers<SuggestOracle.Suggestion> and HasSelectionHandlers<CustomSuggestion>
Can you help me? Sorry for my bad english.
Not sure I understand your problem. Have a look at the following example (really basic but you should get an idea on how to deal with custom suggestions). Hope that helps:
public void onModuleLoad() {
SuggestBox box = new SuggestBox(new CustomOracle<CustomSuggestion>());
box.addSelectionHandler(new SelectionHandler<SuggestOracle.Suggestion>() {
#Override
public void onSelection(SelectionEvent<Suggestion> event) {
String value = ((CustomSuggestion) event.getSelectedItem()).fSomeOtherValue;
Window.alert(value);
}
});
RootPanel.get().add(box);
}
private class CustomOracle<CustomSuggestion> extends SuggestOracle {
private LinkedList<Starter.CustomSuggestion> fStore;
public CustomOracle() {
fStore = new LinkedList<Starter.CustomSuggestion>();
fStore.add(new Starter.CustomSuggestion("2", "two", "foo"));
fStore.add(new Starter.CustomSuggestion("22", "twenty-two", "bar"));
fStore.add(new Starter.CustomSuggestion("222", "two-hundred twenty-two", "w000t"));
}
#Override
public void requestSuggestions(Request request, Callback callback) {
String query = request.getQuery();
LinkedList<Starter.CustomSuggestion> result = new LinkedList<Starter.CustomSuggestion>();
for (Starter.CustomSuggestion entry : fStore) {
if (entry.fDisplay.contains(query)) {
result.add(entry);
}
}
callback.onSuggestionsReady(request, new Response(result));
}
}
private class CustomSuggestion implements Suggestion {
private String fReplace;
private String fDisplay;
private String fSomeOtherValue;
public CustomSuggestion(String display, String replace, String someOtherValue) {
fDisplay = display;
fReplace = replace;
fSomeOtherValue = someOtherValue;
}
#Override
public String getDisplayString() {
return fDisplay;
}
#Override
public String getReplacementString() {
return fReplace;
}
}