How to disbale introspection query in GraphQL-Java? - java

I am using GraphQL-Java version:11.0
From Official GraphQL-Java documenetation I found that I can disable the introspection query as belwo :
GraphQLSchema schema = GraphQLSchema.newSchema()
.query(StarWarsSchema.queryType)
.fieldVisibility(NoIntrospectionGraphqlFieldVisibility.NO_INTROSPECTION_FIELD_VISIBILITY)
.build();
Same has been given in this SO question's answer
But the issue is in above solutions the fieldVisibility is available with object returned by GraphQLSchema.newSchema().
I am building the GraphQL schema as below:
public GraphQLProvider init(GraphQLResolvers graphQLResolvers) {
GraphQLSchema graphQLSchema = buildSchema (typeRegistry, runtimeWiring);
this.graphQL = createInstance (graphQLSchema);
return this;
}
private GraphQLSchema buildSchema (TypeDefinitionRegistry typeRegistry, RuntimeWiring runtimeWiring) {
SchemaGenerator schemaGenerator = new SchemaGenerator();
return schemaGenerator.makeExecutableSchema(typeRegistry, runtimeWiring);
}
private GraphQL createInstance (GraphQLSchema graphQLSchema) {
return GraphQL.newGraphQL(graphQLSchema).build();
}
As you can see in above code, I am not using GraphQLSchema.newSchema() anywhere, so I am not able to set the fieldVisibility for introspectionQuery, can anyone suggest how can I modify above code to accommodate fieldVisibility option?
Any help is much appreciated. Thanks!

The fieldVisibility option is also available on RuntimeWiring, so I just did
RuntimeWiring.Builder builder = graphQLResolvers.newRuntimeWiringBuilder();
builder.fieldVisibility(NoIntrospectionGraphqlFieldVisibility.NO_INTROSPECTION_FIELD_VISIBILITY);
Hope it helps someone :)

Related

How to install or register a Saxon HE 10.3 Configuration? Configuration is not being used

I'm trying to use a custom Configuration for saxon HE 10.3.
The Configuration is not being used. Presumably the config needs to be registered or installed? But how?
Here's my code:
final Configuration config = new net.sf.saxon.Configuration();
/**/ config.setLocalizerFactory(new LocalizerFactory() {
public Numberer getNumberer(final String language, final String country) {
if (language.equals("de")) {
return Numberer_de.getInstance();
} else {
return null;
}
}
});
net.sf.saxon.Transform.main(new String[] {
"-s:source.xml",
"-xsl:stylesheet.xslt",
"-o:result.txt"
});
You really don't want to be running net.sf.saxon.Transform.main from a Java application: use either the s9api or JAXP transformation APIs. The net.sf.saxon.Transform.main interface is designed for use from the command line, and it can therefore only modify the configuration through command line switches. It also has drawbacks like shutting down the Java VM if the transformation fails.
There is a workaround, which is to use the -init option on the command line to trigger user-supplied initialisation code (which has access to the Configuration object), but that's only really digging yourself deeper into your hole. I'd recommend switching to the s9api API.
Documentation: https://saxonica.com/documentation/index.html#!using-xsl/embedding
If you want to change the configuration when running Saxon from the command line, as Michael said, there is the -init option to pass in the name of a class implementing the Initializer interface https://saxonica.com/documentation/index.html#!javadoc/net.sf.saxon.lib/Initializer so you would use roughly e.g.
package com.example;
import net.sf.saxon.option.local.Numberer_de;
import net.sf.saxon.lib.Initializer;
import net.sf.saxon.Configuration;
import net.sf.saxon.lib.LocalizerFactory;
import net.sf.saxon.lib.Numberer;
import javax.xml.transform.TransformerException;
public class MyInitializer implements Initializer {
public override void initialize(Configuration config) throws TransformerException {
config.setLocalizerFactory(new LocalizerFactory() {
public Numberer getNumberer(final String language, final String country) {
if (language.equals("de")) {
return Numberer_de.getInstance();
} else {
return null;
}
}
});
}
}
compile that, put it on the classpath and then run e.g. java -cp saxon-he-10.3.jar;com/example/MyInitializer;net/sf/saxon/option/local/Numberer_de net.sf.saxon.Transform -init:com.example.MyInitializer -s:source.xml -xsl:stylesheet.xslt -o:result.txt.
Or you can subclass net.sf.saxon.Transform.
On the other hand, if you don't want to run Saxon from the command line but from the JAXP API then I think one approach is to create the Configuration e.g.
Configuration config = new Configuration();
config.setLocalizerFactory(new LocalizerFactory() {
public Numberer getNumberer(final String language, final String country) {
if (language.equals("de")) {
return Numberer_de.getInstance();
} else {
return null;
}
}
});
TransformerFactory transformerFactory = new TransformerFactoryImpl(config);
Templates templates = transformerFactory.newTemplates(xsltSource);
What was missing, was how to inject the Config. This worked for me:
import net.sf.saxon.Configuration;
import net.sf.saxon.TransformerFactoryImpl;
import net.sf.saxon.lib.Feature;
final TransformerFactoryImpl factory = (TransformerFactoryImpl) TransformerFactory.newInstance();
factory.getProcessor().setConfigurationProperty(Feature.CONFIGURATION, config);

JDeveloper don't find SignerEPES having xades4j.jar

Im using #lgoncalves code to sign an XML with XADES4J EPES. But however jdeveloper don't find (SignerEPES) when I have the xades4j.jar on my classpath. I let you the image of my library and the code:
Project Library
private static void signBes(Document doc) throws XadesProfileResolutionException, XAdES4jException,
KeyStoreException {
//Document doc = getTestDocument();
Element elemToSign = doc.getDocumentElement();
SignaturePolicyInfoProvider policyInfoProvider = new SignaturePolicyInfoProvider()
{
#Override
public SignaturePolicyBase getSignaturePolicy()
{
return new SignaturePolicyIdentifierProperty(
new ObjectIdentifier("oid:/1.2.4.0.9.4.5", IdentifierType.OIDAsURI, "Policy description"),
new ByteArrayInputStream("Test policy input stream".getBytes()))
.withLocationUrl(""); //<- I really don't know what to put right here.
}
};
KeyingDataProvider kdp = new FileSystemKeyStoreKeyingDataProvider("pkcs12","C:/****/****.pfx",new FirstCertificateSelector(),new DirectPasswordProvider("****"),new DirectPasswordProvider("****"),true);
SignerEPES signer = (SignerEPES) new XadesEpesSigningProfile(kdp, policyInfoProvider).newSigner();
new Enveloped(signer).sign(elemToSign);
}
Link to the sample code on GitHub: https://github.com/luisgoncalves/xades4j/blob/master/src/test/java/xades4j/production/SignerEPESTest.java
EDIT:
I tried to force the import like (import xades4j.production.SignerEPES) but IDE says "Cannot be accessed from outside package" but really don't know what that means
SignerEPES is a package-private class, so application code won't be able to import it. The tests use it just to be sure that the proper type is being returned.
In your code you can just use XadesSigner as the type of your variable.

Code in Persistent EHcache docs not working java

I want to use EHcache in my java project. They have persistent storage support. I have read the docs
https://www.ehcache.org/documentation/2.7/configuration/fast-restart.html and found this code
Configuration cacheManagerConfig = new Configuration()
.diskStore(new DiskStoreConfiguration()
.path("/tmp/file.txt"));
CacheConfiguration cacheConfig = new CacheConfiguration()
.name("my-cache")
.maxBytesLocalHeap(16, MemoryUnit.MEGABYTES)
.maxBytesLocalOffHeap(256, MemoryUnit.MEGABYTES)
.persistence(new PersistenceConfiguration().strategy(Strategy.LOCALTEMPSWAP));
cacheManagerConfig.addCache(cacheConfig);
CacheManager cacheManager = new CacheManager(cacheManagerConfig);
Ehcache myCache = cacheManager.getEhcache("my-cache");
I have imported the dependency but it shows lots of error.
Error I got
'Configuration' is abstract; cannot be instantiated
Please provide some simple steps to make use of this library. I read the docs but the code doesn't get worked. Help me with some solutions.
Found the Answer.
try(PersistentCacheManager persistentCacheManager =
newCacheManagerBuilder()
.with(persistence("/tmp/myProjectCache"))
.withCache("test-cache",
newCacheConfigurationBuilder(
String.class, String.class,
newResourcePoolsBuilder()
.heap(1, EntryUnit.ENTRIES)
.offheap(1, MemoryUnit.MB)
.disk(2, MemoryUnit.MB, true)
)
).build(true)) {
org.ehcache.Cache cache = persistentCacheManager.getCache("test-cache", String.class, String.class);
cache.put("name1","steven");
cache.put("name2","prince");
System.out.println(cache.get("name1"));
System.out.println(cache.get("name2"));
}

When my Spring app runs, it isn't using my TogglzConfig file

I have a large Spring application that is set up without XML using only annotations. I have made some changes to this application and have a separate project with what should be almost all the same code. However, in this separate project, Togglz seems to be using some sort of default config instead of the TogglzConfig file I've set up.
The first sign that something was wrong was when I couldn't access the Togglz console. I get a 403 Forbidden error despite my config being set to allow anyone to use it (as shown on the Togglz site). I then did some tests and tried to see a list of features and the list is empty when I call FeatureContext.getFeatureManager().getFeatures() despite my Feature class having several features included. This is why I think it's using some sort of default.
TogglzConfiguration.java
public enum Features implements Feature {
FEATURE1,
FEATURE2,
FEATURE3,
FEATURE4,
FEATURE5;
public boolean isActive() {
return FeatureContext.getFeatureManager().isActive(this);
}
}
TogglzConfiguration.java
#Component
public class TogglzConfiguration implements TogglzConfig {
public Class<? extends Feature> getFeatureClass() {
return Features.class;
}
public StateRepository getStateRepository() {
File properties = [internal call to property file];
try {
return new FileBasedStateRepository(properties);
} catch (Exception e) {
throw new TogglzConfigException("Error getting Togglz configuration from " + properties + ".", e);
}
}
#Override
public UserProvider getUserProvider() {
return new UserProvider() {
#Override
public FeatureUser getCurrentUser() {
return new SimpleFeatureUser("admin", true);
}
};
}
}
SpringConfiguration.java
#EnableTransactionManagement
#Configuration
#ComponentScan(basePackages = { "root package for the entire project" }, excludeFilters =
#ComponentScan.Filter(type=FilterType.ANNOTATION, value=Controller.class))
public class SpringConfiguration {
#Bean
public TransformerFactory transformerFactory() {
return TransformerFactory.newInstance();
}
#Bean
public DocumentBuilderFactory documentBuilderfactory() {
return DocumentBuilderFactory.newInstance();
}
#Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
My project finds a bunch of other beans set up with the #Component annotation. I don't know if the problem is that this component isn't being picked up at all or if Togglz simply isn't using it for some reason. I tried printing the name of the FeatureManager returned by FeatureContext.getFeaturemanager() and it is FallbackTestFeatureManager so this seems to confirm my suspicion that it's just not using my config at all.
Anyone have any ideas on what I can check? I'm flat out of ideas, especially since this is working with an almost completely the same IntelliJ project on my machine right now. I just can't find out what's different about the Togglz setup or the Spring configurations. Thanks in advance for your help.
I finally had my light bulb moment and solved this problem. In case anyone else has a similar issue, it seems my mistake was having the Togglz testing and JUnit dependencies added to my project but not limiting them to the test scope. I overlooked that part of the site.
<!-- Togglz testing support -->
<dependency>
<groupId>org.togglz</groupId>
<artifactId>togglz-testing</artifactId>
<version>2.5.0.Final</version>
<scope>test</scope>
</dependency>
Without that scope, I assume these were overriding the Togglz configuration I created with a default test configuration and that was causing my issue.

How to access user-defined value in a bolt's getComponentConfiguration() when using storm?

I want to initialize my redis address dynamicly by command line, And use it before a bolt's open method:
public class RunMyTopology {
#Parameter(names = { "-topologyName"}, description = "Topology name.")
private static String TOP_NAME = "demo";
#Parameter(names = { "-redisAddr"}, description = "Redis host address.", validateWith = IPValidator.class)
public static String REDIS_ADDR = "172.16.3.142";
public static void main(String[] args) throws AlreadyAliveException, InvalidTopologyException {
new JCommander(new RunMyTopology(), args);
TopologyBuilder builder = new TopologyBuilder();
builder.setSpout("spout", new Spout(REDIS_ADDR), 1);
builder.setBolt("fixerBolt",new FixerBolt(REDIS_Addr),1).fieldsGrouping("spout", new Fields("busId"));
// And many other bolts need REDIS_ADDR
Config conf = new Config();
conf.put(Config.TOPOLOGY_WORKERS, 22);
StormSubmitter.submitTopology(TOP_NAME, new Conf, builder.createTopology());
}
}
Now I can achive it by passing constructor parameters, but if I have many
config values like redis address, this way looks ugly. How to notify the changed value in other way?
Unfortunately, there is no externalization of properties in Apache Storm.
But you can use many librairies that are available for this purpose, such as Spring (placeholder API) or Apache Commons Configuration (I personally use it with storm as it is quite lightweight and does that job well enough).
If you plan on using Commons Configuration:
define your property files for different environment DEV, PROD...
you must parse a commons configuration first with support for property overwritting (with an environment or system variable for instance)
then get all properties inside to put them into Storm Config (filter some if you take all system properties, it can be full of crap)
finally you can start your cluster
Hope that helps.
Here is a link to the documentation.
http://commons.apache.org/proper/commons-configuration/userguide_v1.10/overview.html#Using_Configuration

Categories

Resources