Disabling Swagger Bundle in DropWizard - java

I am looking to disable the swagger functionality / endpoint in a production environment based on a config value.
How would I go about this?
I believe the best way to achieve this is not to add the bundle during the execution of the initialize method when a DropWizard application first starts.
The issue with this solution is that you cannot access the configuration get methods that are populated from the values in the YAML/YML file. These values are available are available when we the application gets to the run method.
Here is my initialise method from the application class
#Override
public void initialize(Bootstrap<Configuration> bootstrap) {
LOGGER.debug("initialize");
bootstrap.setConfigurationSourceProvider(new SubstitutingSourceProvider(bootstrap.getConfigurationSourceProvider(),
new EnvironmentVariableSubstitutor(false)));
bootstrap.addBundle(new SwaggerBundle<Configuration>() {
#Override
protected SwaggerBundleConfiguration getSwaggerBundleConfiguration(Configuration configuration) {
return configuration.swaggerBundleConfiguration;
}
});
}
If I need to clarify more please let me know.
Thanks in advance.

You can set an environment variable in production and use it to decide whether to include SwaggerBundle or not. For example:
if (!"prod".equalsIgnoreCase(System.getenv("ENVIRONMENT"))) {
bootstrap.addBundle(new SwaggerBundle<Configuration>() { ... }
}

I was using an older version of DropWizard at the time.
After updating, there were new methods available including setIsEnabled()
This is what was added to solve the issue.
bootstrap.addBundle(new SwaggerBundle<Configuration>() {
#Override
protected SwaggerBundleConfiguration getSwaggerBundleConfiguration(Configuration configuration) {
if(!configuration.getSwaggerEnabled()){
configuration.swaggerBundleConfiguration.setIsEnabled(false);
}
return configuration.swaggerBundleConfiguration;
}
});
}
Thanks,

Related

Logging Azure Function

Is there a way to view logging of my Azure Function App without the use of Application Insights?
Can I write the logging of my Function app to a separate file that I can view? (edit) If so, how?
Edit: I should have mentioned that I am using Java.
Diagnostic Settings will be of help here. You can enable diagnostics to publish the logs to a storage account.
To set the settings. Search for Diagnostic settings in the search-pane of your function app.
And then enable by providing the storage account details:
For full information refer: https://learn.microsoft.com/en-us/azure/azure-functions/functions-monitor-log-analytics?tabs=java
The benefit of this is: that you can continue to log using the default logging framework that the azure-functions provide. There isn't any code change that is required.
yes, I do agree with the point mentioned by #Thiago Custodio. you can use serilog in the Azure functions to view your logs.
Here is the code provided by #Ivan Yang in this So for using Serilg in Azure functions.
[assembly: WebJobsStartup(typeof(Startup))]
namespace MyApp
{
public class Startup : IWebJobsStartup
{
public void Configure(IWebJobsBuilder builder)
{
//other code
builder.Services.AddLogging();
}
}
public class Functions
{
//other code
private ILogger _log;
public Functions(ILoggerFactory loggerFactory)
{
_log = loggerFactory.CreateLogger<Functions>();
}
[FunctionName("Token")]
public async Task<IActionResult> Function1(
[HttpTrigger()]...)
{
_log.LogInformation("Function1 invoked");
}
}
}

Android annotation processing - generate different code for different build flavor

I'm building a library that requires some annotation processing to generate code. I now run into an issue that the release build doesn't need to have as much code as the debug build does (since this is a library for modifying configuration variants - primarily used for testing purposes). The following code illustrates the situations. Let's say I want to create a class ConfigManager from some annotated classes and properties. In debug builds, I need this much:
public class ConfigManager {
public Class getConfigClass() {
return abc.class;
}
public void method1() {
doSomething1();
}
public void method2() {
doSomething2();
}
public void method3() {
doSomething3();
}
}
While in release builds, I only need this much:
public class ConfigManager {
public Class getConfigClass() {
return abc.class;
}
}
I have a feeling it may be possible by writing a Gradle plugin to check for build flavor at compile time and invoke a different processor/or somehow pass a parameter to a processor to generate different code. However this topic is pretty new to me so I'm not sure how to achieve this. A couple hours of googling also didnt help. So I'm wondering if anyone could give me a direction or example? Thanks
Pass an option (release=true/false) to your processor.
From javac https://docs.oracle.com/javase/8/docs/technotes/tools/windows/javac.html
-Akey[=value]
Specifies options to pass to annotation processors. These options are not interpreted by javac directly, but are made available for use by individual processors. The key value should be one or more identifiers separated by a dot (.).
In combination with Processor.html#getSupportedOptions https://docs.oracle.com/javase/8/docs/api/javax/annotation/processing/Processor.html#getSupportedOptions
Returns the options recognized by this processor. An implementation of the processing tool must provide a way to pass processor-specific options distinctly from options passed to the tool itself, see getOptions.
Implementation outline:
public Set<String> getSupportedOptions() {
Set<String> set = new HashSet<>();
set.add("release");
return set;
}
// -Arelease=true
boolean isRelease(ProcessingEnvironment env) {
return Boolean.parseBoolean(env.getOptions().get("release"));
}
See Pass options to JPAAnnotationProcessor from Gradle for how to pass options in a gradle build.

Picocontainer 2.14.3 and AOP

I'm trying to use AOP with picocontainer.
so far I found in the documentation:
http://picocontainer.codehaus.org/interception.html
pico = new DefaultPicoContainer();
pico.as(INTERCEPT).addComponent(Apple.class, BraeburnApple.class);
and then create the interceptor, but looking through the code, I cannot find the INTERCEPT property anywhere.
as receives a Properties value, which pico implements in Characteristics class.
anyone has a clue, or has implemented it before and knows how to keep with it?
Thanks
looks like the property for this Behavior is somehow missing in this pico version, check org.picocontainer.Characteristics in older versions, I really hope it was implemented somewhere :)
Also there's old styled way for interception in pico: http://www.markhneedham.com/blog/2008/11/11/logging-with-pico-container/
Since the 2.14.3 org.picocontainer.behaviors still have these classes, I suppose this way is ok
This worked for me. First, create a proxy by extending a bean:
public static class ChangeMapInfoEndpointInterceptor extends MapInfoRoutingManagementBean {
#Override
public void setEndpoint(String endpoint) {
System.out.println("setEndpoint called");
}
}
Then pass it to the intercepting-styled container:
MutablePicoContainer context = new PicoBuilder().withBehaviors(new Intercepting()).build();
context.addComponent(MapInfoRoutingManagement.class, MapInfoRoutingManagementBean.class);
Intercepted intercepted = context.getComponentAdapter(MapInfoRoutingManagement.class).findAdapterOfType(Intercepted.class);
intercepted.addPostInvocation(MapInfoRoutingManagement.class, new ChangeMapInfoEndpointInterceptor());

Java - Reset or Specialize Security Manager

I am trying to build a Plugin System in java without resorting to special libraries.
As of now, I am able to load and process my plugins. However, I need to define a special Security Manager which disables any access to file deletion and others.
This Security Manager should only keep plugins in place, because the core of my system has to perform some actions plugins can't. As a result, I cannot set the Security Manager using the System class, or it will affect my system's core as well.
I've tried to "reset" the default Security Manager after loading the plugins, but I was unable to do that. Even if I was able, the plugins would end up executing the system's current Security Manager, not their own.
I would like to know if there is a way to encapsulate classes to specific Security Managers.
On top of my head, I was thinking on looking the stack trace and, if a plugin class is found as a caller, forbid the actions they should not perform, but I fear this will prove to be a little ineffective performance-wise.
As soon as I am able, I will post the code to my Security Manager in order to help with ideas.
Here is the code for my Security Manager:
package org.zeh.filemanager.core.controllers.util;
import java.io.FileDescriptor;
/**
* #author José Ricardo Carvalho Prado de Almeida
*/
public class PluginSecurityManager extends SecurityManager {
#Override
public void checkRead(FileDescriptor filedescriptor) {
super.checkRead(filedescriptor);
}
#Override
public void checkRead(String filename) {
super.checkRead(filename);
}
#Override
public void checkRead(String filename,
Object executionContext) {
//
super.checkRead(filename,
executionContext);
}
#Override
public void checkWrite(FileDescriptor filedescriptor) {
throw new SecurityException("Plugin is trying to write files.");
}
#Override
public void checkWrite(String filename) {
throw new SecurityException("Plugin is trying to write files.");
}
#Override
public void checkDelete(String file) {
super.checkDelete(file);
throw new SecurityException("Plugin is trying to delete files.");
}
#Override
public void checkExec(String cmd) {
super.checkExec(cmd);
throw new SecurityException("Plugin is trying to create subprocesses.");
}
#Override
public void checkExit(int status) {
super.checkExit(status);
throw new SecurityException("Plugin is trying to finalize the JVM.");
}
#Override
public void checkCreateClassLoader() {
super.checkCreateClassLoader();
throw new SecurityException("Plugin is trying to create ClassLoaders.");
}
}
I have found a question (How to implement Java plugin security safely?), that is very similar to mine but the answers do not really fit in my context, where external libraries are not desired.
I forgot to mention that I do have a custom Class Loader that is working perfectly as of now.
I've designed the program so each kind of plugin would have a special Class Loader and such loader would have it's own Security Manager, to restrict different plugins based on functionality.
The only reason this design does not work is because of those Security Managers. If I ignore the use of Security Managers, the system does everything it is supposed to, although it is not secure.
Does anyone have a probable solution for this problem?
Thank you.

Monitoring ng test runs from other eclipse plugin

I am developing an eclipse plugin that shows the user links to test logs. In the current implementation we register a jUnit run listener that updates the view whenever a suite has been run and this works fine, problem is that the test framework now also support TestNG and we will need the equivalent functionality from the TestNG plugin if the user runs a TestNG testcase.
I found this feature request http://jira.opensymphony.com/browse/TESTNG-313 which suggests that the functionality I am looking for is there to use, at least that´s how I interpret it. Anyway, I can´t seem to get it to work. I try to create and define different objects in the view setup that should listen for ng-runs and calls to for example onFinish() but I have not found a way to "register" the listening class the way you are if you are defining a regular listener from the suite.xml or code. The TestNG class seems to be a singleton but only for every testrun, not for monitoring the plugin for whenever a suite is run. The TestNGPlugin class does not seem to have appropriate methods. Just implementing a TestListenerAdapter or ITestListener interface as a private class does not do the trick.
Does anyone know which is the most appropriate class or interface to implement for this and if needed, how they should be registered?
Btw I am using Eclipse 3.7.0 and TestNG 6.1.1.
I found another way around the problem, probably a better solution in the end. I monitor the org.eclipse.debug.core.DebugPlugin for any launch of any kind and do the update depending on that. This little piece of code made it work.
ILaunchesListener2 runListener = new ILaunchesListener2() {
#Override
public void launchesAdded(ILaunch[] arg0) {
}
#Override
public void launchesChanged(ILaunch[] arg0) {
}
#Override
public void launchesRemoved(ILaunch[] arg0) {
}
#Override
public void launchesTerminated(ILaunch[] arg0) {
Display.getDefault().asyncExec(new Runnable() {
public void run() {
updateTestRunList();
viewer.setInput(testRuns);
viewer.refresh();
}
});
}
};
DebugPlugin.getDefault().getLaunchManager().addLaunchListener(runListener);

Categories

Resources