Initialize Hats methods using GenericPortlet class - java

I am replacing PortletAdapter with GenericPortlet class in code. I followed this link - https://help.hcltechsw.com/digital-experience/9.5/dev-portlet/jsrmig.html. I am trying to initialize HATS-Host Access Transformation Services methods (see initializeHats() method) and it needs ServletConfig as a parameter. But I am not able to access the getServletConfig() method in the GenericPortlet class. I passed getPortletConfig() but got a null pointer exception. Below are my old code and new code. What is the replacement for the getServletConfig()?
Old code:
package abcpostavailablefreight;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import org.apache.jetspeed.portlet.*;
import org.apache.jetspeed.portlet.event.*;
import com.ibm.hats.runtime.connmgr.Runtime;
import com.ibm.hats.util.LicenseManager;
public class AbcPostAvailableFreightPortlet extends PortletAdapter implements ActionListener {
public void init(PortletConfig portletConfig) throws UnavailableException {
super.init(portletConfig);
}
public void initializeHats() {
initHATS = true;
//Initialize and activate the HATS runtime RAS functions,
// including tracing, logging, PII retrieval, locale.
com.ibm.hats.util.Ras.initializeRas(getServletConfig());
//Create the license manager
LicenseManager.getInstance();
//Initialize Host Publisher/connection management runtime
Runtime.initRuntime(getServletConfig());
}
}
New Code:
package abcpostavailablefreight;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import javax.portlet.*;
import javax.portlet.UnavailableException;
import javax.servlet.*;
import javax.servlet.http.HttpSession;
public class AbcPostAvailableFreightPortlet extends GenericPortlet{
public void init(PortletConfig portletConfig) throws UnavailableException, PortletException {
super.init(portletConfig);
}
public void initializeHats(ActionRequest request) {
initHATS = true;
//Initialize and activate the HATS runtime RAS functions,
// including tracing, logging, PII retrieval, locale.
com.ibm.hats.util.Ras.initializeRas(getPortletConfig());
//Create the license manager
LicenseManager.getInstance();
//Initialize Host Publisher/connection management runtime
Runtime.initRuntime(getPortletConfig());
}
}

Related

Multiple functions for the same path in jax.ws.rs?

Lets say I wanted in implement readonly behaviour on my application (not allowing posts/puts). Could I do this by disabling these types/setting a #POST/#PUT that catches requests on any endpoint? (As opposed to putting a boolean flag on every single post/put in my application
You could add a filter, disallowing all the methods you don't want to support:
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.SecurityContext;
import javax.ws.rs.ext.Provider;
#Provider
public class AuthorizationRequestFilter implements ContainerRequestFilter {
private final List<String> disallowed=Arrays.asList("POST","PUT","DELETE","PATCH");
#Override
public void filter(ContainerRequestContext requestContext)
throws IOException {
if (disallowed.contains(requestContext.getMethod())){
requestContext.abortWith(Response
.status(Response.Status.FORBIDDEN)
.entity("User cannot modify the resource.")
.build());
}
}
}

Cannot make a static reference to the non-static method --- from the type --- Java Bukkit Minecraft

I know there have been plenty of other posts like this from people trying to find their problem in their static class and I have read them but to no avail. I am trying to make a minecraft bukkit plugin for bedwars and when trying to use world.--- I constantly get these errors(Cannot make a static reference to the non-static method getPlayers from the type World) and cannot find where the static class is originating from. Here is my code:
package me.fitch.bedwars.timers;
import java.util.List;
import org.bukkit.Bukkit;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.World;
import org.bukkit.entity.Player;
import me.fitch.bedwars.main;
public class starttimer implements Listener {
private main plugin;
public starttimer(main plugin) {
this.plugin = plugin;
Bukkit.getPluginManager().registerEvents(this, plugin);
}
#EventHandler
public void startjoin(PlayerJoinEvent e)
{
Object [] players = World.getPlayers().toArray(); //error here
if(players.length == 8)
{
//start countdown
}
}
}
Hope you can help and that I'm not just blind
Thanks :)
Edit: after instantiating World server = new World(); I am now getting "Cannot instantiate the type World" errors, thanks for the help so far guys, hope you can help with this :)
Edit 2: so e.getPlayer().getWorld() works now so thanks but I'm now having issues in my main class where e is not a thing
package me.fitch.bedwars;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.plugin.java.JavaPlugin;
import me.fitch.bedwars.listeners.beddestroy;
public class main extends JavaPlugin {
private main plugin;
public main(main plugin) {
this.plugin = plugin;
}
#Override
public void onEnable()
{
World.setSpawnLocation(Integer.parseInt( plugin.getConfig().getString("respawn_pointx")), Integer.parseInt( plugin.getConfig().getString("respawn_pointx")) + 1,Integer.parseInt( plugin.getConfig().getString("respawn_pointz")));
new beddestroy(this);
}
}
You will want your listener in its own class myListener.java.
From within the listener events in that class you should be able to do everything you need to do.
I like to create a public static Plugin object in case you ever need to reference the specific instance of the Plugin object from any other class in your plugin.
You will register the listener like this in Main.onEnable()
package myPlugin;
import myPlugin.myListenerClass;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
public class Main extends JavaPlugin {
public static Plugin instance;
#Override
public void onEnable() {
instance = this;
PluginManager my_pm = getServer().getPluginManager();
my_pm.registerEvents(new myListenerClass(), this);
}
}
Your myListenerClass.java will be setup something like the following:
package myPlugin;
import org.bukkit.Bukkit;
import org.bukkit.event.Listener;
public class myListenerClass implements Listener {
#EventHandler
public void onJoin(PlayerJoinEvent event) {
System.out.println("PlayerJoinEvent was triggered!");
int playerCount = Bukkit.getServer().getOnlinePlayers().size();
if (playerCount == 8) {
// start countdown
}
}
}

Jersey 3 - Configuring binding with bindFactory

Using Jersey 3.0.1, I am struggling to get binding working.
I have this binding module with the factories below:
public static class MyBinder extends AbstractBinder {
#Override
protected void configure() {
LOG.info("Attempting to configure binder");
bindFactory(DataSourceFactory.class).to(HikariDataSource.class).in(Singleton.class);
bindFactory(JooqConfigFactory.class).to(Configuration.class).in(Singleton.class);
bindFactory(DSLContextFactory.class).to(DSLContext.class).in(Singleton.class);
LOG.info("Configured binder");
}
}
public static class DataSourceFactory implements Supplier<HikariDataSource> {
#Override
public HikariDataSource get() {
...
return new HikariDataSource(config);
}
}
public static class JooqConfigFactory implements Supplier<Configuration> {
#Inject
HikariDataSource dataSource;
#Override
public Configuration get() {
...
return conf;
}
}
public static class DSLContextFactory implements Supplier<DSLContext> {
#Inject
Configuration config;
#Override
public DSLContext get() {
return DSL.using(config);
}
}
Then I have the setup for my Servlet using embedded Jetty:
public void start() throws Exception {
int port = appConfig.getProperty("http.port", 9998);
Server server = new Server(port);
ServletContextHandler ctx =
new ServletContextHandler(ServletContextHandler.NO_SESSIONS);
ctx.setContextPath("/");
server.setHandler(ctx);
ResourceConfig config = new JerseyConfig();
ServletHolder servlet = new ServletHolder(new ServletContainer(config));
servlet.setInitOrder(1);
ctx.addServlet(servlet, "/*");
server.start();
server.join();
}
public static class JerseyConfig extends ResourceConfig {
public JerseyConfig() {
packages("com.sodonnell.jersey", "jersey.config.server.provider.packages");
register(new MyBinder());
}
}
And in my Rest service I simply try to inject a private instance variable:
public MyClass {
#Inject // javax.inject.Inject
private DSLContext dslContext;
}
However this dslContext is always null. I can see from the logs, that it prints the LOG.info("Configured binder"); message. However putting similar logs in my factory classes show they never get called.
Has anyone got any idea what I am missing?
EDIT
To make things simpler, I created this class:
public class SimpleClass {
private static Logger LOG = LoggerFactory.getLogger(SimpleClass.class);
public SimpleClass() {
LOG.info("Call the simple class constructor");
}
Changed my binder module:
import com.google.inject.Injector;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.glassfish.jersey.internal.inject.AbstractBinder;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.servlet.ServletContainer;
import org.jooq.Configuration;
import org.jooq.DSLContext;
import org.jooq.SQLDialect;
import org.jooq.impl.DSL;
import org.jooq.impl.DefaultConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.io.IOException;
import java.util.Properties;
import java.util.function.Supplier;
...
// This is a nested class
public static class MyBinder extends AbstractBinder {
#Override
protected void configure() {
LOG.info("Attempting to configure binder");
bind(new SimpleClass()).to(SimpleClass.class);
}
}
Then attempted to inject just SimpleClass:
package com.sodonnell.hdfs3.rest;
import com.sodonnell.hdfs3.SimpleClass;
import com.zaxxer.hikari.HikariDataSource;
import jakarta.ws.rs.DELETE;
import jakarta.ws.rs.HEAD;
import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PUT;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.Response;
import org.jooq.DSLContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.inject.Inject;
#Inject
private SimpleClass simpleClass;
...
But its still null, although I see both the log messages. There must be some fundamental setup I am missing.
Full cut down code with the SimpleClass example at:
github.com/sodonnel/jerseyBind
The answer is quite simple. You are using Jersey 3.0 which has switched to the new Jakarta naming. javax is thrown out the window - this includes javax.inject. All the javax package names have now been changed to jakarta. So to get the inject to work, the #Inject import should be
import jakarta.inject.Inject;
This change is part of the change of Java EE to Jakarta EE Starting from Jakarta EE 8 to Jakarta EE 9, all the namespacing has changed from javax to jakarta. So things like javax.servlet will now be jakarta.servlet. Weird, yes a huge breaking change with no backward compatibility.
In your case you have all the correct components to work with Jakarta (i.e. Jersey 3.0 and Jett 11), but you just need to make use of the new namespacing. Notice all the JAX-RS imports are now jakarta also.

AEM 6.3 - Creating Event handler using OSGi R6 annotations

I have created an Event handler by following https://github.com/nateyolles/aem-osgi-annotation-demo/blob/master/core/src/main/java/com/nateyolles/aem/osgiannotationdemo/core/listeners/SampleOsgiResourceListener.java and it works fine. However, I get the warning "The field SlingConstants.TOPIC_RESOURCE_ADDED is deprecated". I did some searching and found this thread :https://forums.adobe.com/thread/2325819
Here are the challenges that I am facing:
1) I want to create a separate configuration interface for my event handler. I tried this and it isn't working
package com.aem.sites.interfaces;
import org.apache.sling.api.SlingConstants;
import org.osgi.service.event.EventConstants;
import org.osgi.service.metatype.annotations.AttributeDefinition;
import org.osgi.service.metatype.annotations.AttributeType;
import org.osgi.service.metatype.annotations.ObjectClassDefinition;
#ObjectClassDefinition(name = "Temperature Listener Configuration")
public #interface TemperatureListenerConfiguration {
#AttributeDefinition(
name = EventConstants.EVENT_FILTER,
description = "Configurable paths for temperature event listener",
type = AttributeType.STRING
)
String getPaths() default "/content/aemsite/en/jcr:content/root/responsivegrid/banner";
#AttributeDefinition(
name = EventConstants.EVENT_TOPIC,
description = "Event types",
type = AttributeType.STRING
)
String[] getEventTypes() default {SlingConstants.TOPIC_RESOURCE_ADDED,SlingConstants.TOPIC_RESOURCE_CHANGED, SlingConstants.TOPIC_RESOURCE_REMOVED};
}
package com.aem.sites.listeners;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Modified;
import org.osgi.service.event.Event;
import org.osgi.service.event.EventHandler;
import org.osgi.service.metatype.annotations.Designate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.aem.sites.interfaces.TemperatureListenerConfiguration;
#Component(immediate=true,
service=EventHandler.class,
configurationPid = "com.aem.sites.listeners.EventHandler")
#Designate(ocd=TemperatureListenerConfiguration.class)
public class TemperaturePropertyListener implements EventHandler{
private final Logger logger = LoggerFactory.getLogger(getClass());
#Override
public void handleEvent(Event event) {
logger.info("*********************Event handler*****************************");
}
#Activate
#Modified
public void activate(TemperatureListenerConfiguration config) {
//config.getPaths();
logger.info("**************************TemperaturePropertyListener******************activate**********************");
}
}
I also want the solution for SlingConstants deprecated issue. Not sure if ResourceChangeListener is the answer to my problem and if yes then how everything is going to work together in the code.
Thanks in advance
===============================
Latest Code
package com.aem.sites.listeners;
import java.util.List;
import org.apache.sling.api.resource.observation.ResourceChange;
import org.apache.sling.api.resource.observation.ResourceChangeListener;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Modified;
import org.osgi.service.metatype.annotations.Designate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.aem.sites.interfaces.TemperatureListenerConfiguration;
#Component(immediate=true,
service=ResourceChangeListener.class,
configurationPid = "com.aem.sites.listeners.TemperaturePropertyListener")
#Designate(ocd=TemperatureListenerConfiguration.class)
public class TemperaturePropertyListener implements ResourceChangeListener{
private final Logger logger = LoggerFactory.getLogger(getClass());
#Override
public void onChange(List<ResourceChange> changes) {
for (final ResourceChange change : changes) {
logger.info("**************************TemperaturePropertyListener******************change type**********************"+change.getType());
}
}
#Activate
#Modified
public void activate(TemperatureListenerConfiguration config) {
//config.getPaths();
logger.info("**************************TemperaturePropertyListener******************activate**********************");
}
}
The Interface
package com.aem.sites.interfaces;
import org.apache.sling.api.resource.observation.ResourceChangeListener;
import org.osgi.service.metatype.annotations.AttributeDefinition;
import org.osgi.service.metatype.annotations.AttributeType;
import org.osgi.service.metatype.annotations.ObjectClassDefinition;
#ObjectClassDefinition(name = "Temperature Listener Configuration")
public #interface TemperatureListenerConfiguration {
#AttributeDefinition(
name = ResourceChangeListener.PATHS,
description = "Configurable paths for temperature event listener",
type = AttributeType.STRING
)
String[] getPaths() default {"/content/aemsite/en/jcr:content/root/responsivegrid/banner"};
#AttributeDefinition(
name = ResourceChangeListener.CHANGES,
description = "Event types",
type = AttributeType.STRING
)
String[] getEventTypes() default {"ADDED","REMOVED","CHANGED","PROVIDER_ADDED", "PROVIDER_REMOVED"};
}
Looking at the Javadoc for org.apache.sling.api.SlingConstants in sling 9 documentation here: http://sling.apache.org/apidocs/sling9/org/apache/sling/api/SlingConstants.html
it tells you specifically that TOPIC_RESOURCE_ADDED is deprecated:
Deprecated. Register a ResourceChangeListener instead
Read the documentation for ResourceChangeListener, additionally, you can take a look at a sample SCR service impl from ACS Samples:
It should not be hard to convert that to R6 declarative service.
Also, here are two examples from the sling project ResourceBackedPojoChangeMonitor and OsgiObservationBridge
Try to mimic those classes with the properties in the same class.

JDepend Dependency Constraint Failing

I'm using JDepend to analyze my architecture and create structural tests to verify dependency within a Layered architecture. The two relevant layers are com.domain and com.infrastructure. Domain concretely depends on the Infrastructure layer.
Why is the following test failing?
import java.io.IOException;
import jdepend.framework.DependencyConstraint;
import jdepend.framework.JDepend;
import jdepend.framework.JavaPackage;
import junit.framework.TestCase;
public class DependencyTest extends TestCase {
private JDepend jdepend;
#Override
public void setUp() throws IOException {
jdepend = new JDepend();
jdepend.addDirectory("build/classes/com");
}
public void testDomainDependsOnInfastructure_ShouldBeTrue() {
DependencyConstraint constraint = new DependencyConstraint();
JavaPackage domainPackage = constraint.addPackage("com.domain");
JavaPackage infastructurePackage = constraint.addPackage("com.infrastructure");
domainPackage.dependsUpon(infastructurePackage);
jdepend.analyze();
assertEquals("Domain doesn't depend on Infrastructure layer", true, jdepend.dependencyMatch(constraint));
}
}
jdepend.analyze() returns the relevant packages, so I do know it is finding my code. Any ideas?
Figured it out. JDepend's match function checks all packages, including libraries. I had to custom load it with just the packages I wanted. Here's the code that resolved my problem, if anyone ever runs into this problem.
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import jdepend.framework.DependencyConstraint;
import jdepend.framework.JDepend;
import jdepend.framework.JavaPackage;
import junit.framework.TestCase;
public class DependencyTest extends TestCase {
private JDepend jdepend;
#Override
public void setUp() throws IOException {
jdepend = new JDepend();
jdepend.addDirectory("build/classes/com");
}
public void testDomainDependsOnInfastructure_ShouldBeTrue() {
DependencyConstraint constraint = new DependencyConstraint();
JavaPackage distribution = constraint.addPackage("com.distribution");
JavaPackage domainPackage = constraint.addPackage("com.domain");
JavaPackage infastructurePackage = constraint.addPackage("com.infrastructure");
distribution.dependsUpon(domainPackage);
domainPackage.dependsUpon(infastructurePackage);
jdepend.analyze();
Collection<JavaPackage> actual = new ArrayList<JavaPackage>();
actual.add(domainPackage);
actual.add(distribution);
actual.add(infastructurePackage);
assertEquals("Domain doesn't depend on Infrastructure layer", true, constraint.match(actual));
}
}

Categories