Categories
discuss

Difference between interceptors and decorators

Are there any differences between interceptors and decorators in Java? Strictly speaking, can I implementing things with decorators which are not possible with interceptors and vice versa?

Except the problem that I would have to examine the method name to add method-specific behavior in an interceptor:

Interceptor:

@Nice
@Interceptor
public class NiceGreeterInterceptor {
  @AroundInvoke
  public Object decorate(InvocationContext ic) throws Exception {
    Method method = ic.getMethod();
    String methodName = method.getName();
    Object result = ic.proceed();
    if (methodName.equals("greet")) {
      return "NEW " + result;
    }
  }
}

Decorator:

@Decorator
public class GreeterDecorator implements Greeter {
  @Inject
  @Any
  @Delegate
  private Greeter greeter;

  @Override
  public String greet() {
    return "NEW " + greeter.greet();
  }
}

Or is it legitimate to say that I can reproduce all the behavior of decorators with interceptors but it is more comfortable to use decorators?

Answer

Decorator

One difference would be, as your example shows it, with decorator you usually write 1 decorator per 1 decorated class/interface.

Decorator example

interface Worker {
    void work();
}

class Decorated implements Worker {

    public void work() {

    }
}

class DecoratorByInheritance extends Decorated {

    public void work() {
        // pre
        super.work();
        // post
    }
}

class DecoratorByComposition implements Worker {

    Worker decorated;

    DecoratorByComposition(Worker decorated) {
        this.decorated = decorated;
    }

    public void work() {
        // pre
        this.decorated.work();
        // post
    }
}

Interceptor

With interceptors, which are part of the AOP concept, you write 1 interceptor for a bunch of classes / methods, e.g. you intercept all DAO methods and make sure a transaction is open before the invocation and closed after it.

Interceptor example

Declare a pointcut (what to match), here you match any method from the MyDao class that starts with insert, has any arguments and any return type.

@Pointcut("execution(* com.example.dao.MyDao.insert*(..))")
public void insertPointcut() {
}

Then you declare an around advice which references the pointcut

@Around(value = "com.example.SystemArchitecture.insertPointcut()")
public void interceptMethod(ProceedingJoinPoint pjp) {
        // do pre-work
        Object retVal = pjp.proceed();
        // do post work
        return retVal;
    }
}

Interceptors are more flexible but imagine you change the method name, if you use a decorator, you’ll probably get a compiler error, with interceptors, it will just not match and not execute your ‘around’ logic.

Categories
discuss

Gradle: configuration runtime declares a dependency on configuration default which is not declared in the module descriptor for

Can you tell me why when I run gradle I get this error:

Error:Module version trestGradle:trestGradle:1.0-SNAPSHOT, 
configuration 'runtime' declares a dependency on 
configuration 'default' which is not declared in the module 
descriptor for it.develop:myLib:1.0.0"

What is needed to be declared on the ivy.xml (module descriptor)?

  • MyLib is on an internal ivy repository

  • I checked:credentials, ivy url and the pattern

build.gradle:

group 'trestGrad'
version '1.0-SNAPSHOT'

apply plugin: 'java'

sourceCompatibility = 1.5

configurations {
    compile
}

repositories {
    ivy {
        url = 'http://example.com/artifactory/cst'
        credentials {
            username = "user"
            password = "pass123"
        }
        layout('pattern') {
            // Pattern to resolve Ivy descriptor files.
            ivy '[organization]/[module]/[revision]/[type]s/ivy.xml'
            // Pattern to resolve files.
            artifact '[organization]/[module]/[revision]/[type]s/[module].[ext]'
        }
    }
}

dependencies {
    compile "it.develop:myLib:1.0.0"
}

Answer

See here.

You need to specify the configuration for your dependency. Failing which ivy assumes default configuration and hence your error message.

Categories
discuss

no window object present webpack nodejs

I’m using webpack with babel to compile my ecmascript 6 code. Everything works fine but if I add certain dependeciens like the requests npm package. Here are my files:

main.js

import os from 'os'

export class User {

  constructor(username) {
    this.username = username;
  }

  register() {
    console.log("registering...");
  }
}

var client = new User("hey")


console.log(user.register());

webpack config:

var webpack = require('webpack')

module.exports = {
  entry: [
    './src/main.js'
  ],
  output: {
    path: "dist",
    publicPath: "/dist/",
    filename: "stela.js"
  },
  watch: false,
  module: {
    loaders: [{
      test: /.js$/,
      // excluding some local linked packages.
      // for normal use cases only node_modules is needed.
      exclude: /node_modules/,
      loader: 'babel'
    }, {
      test: /.json$/,
      loader: 'json-loader'
    }]
  },
  externals: {
    fs: '{}',
    tls: '{}',
    net: '{}',
    console: '{}'
  },
  babel: {
    presets: ['es2015'],
    plugins: ['transform-runtime']
  },
  resolve: {
    modulesDirectories: ['node_modules']
  }
}

Now if I run webpack and then run node dist/stella.js everything works fine it logs out registering...; however, if I add certain dependencies like the requests npm package:

...
import request from 'request'
...

I run webpack everything compiles down with no errors but then I try running node dist/stella.js and I get this error:

throw new Error('no window object present');

Answer

By default, Webpack is set up to target the browser, not a Node environment. Try setting target in your config:

module.exports = {
    // ...
    target: "node",
    // ...
}
Categories
discuss

Trying to load a local page into JavaFX webEngine

I have a webView component on a tab in my JavaFX application which I am trying to load an locally stored HTML page into:

WebView browser = new WebView();
WebEngine webEngine = browser.getEngine();
webEngine.load("/webView/main.html");

My html document is (possibly incorrectly) stored in the following location:

Location of my HTML document

where com.cds.gui contains the class where I am attempting to load the file. If I print out webEngine.getDocument() I get null – i.e. the document isn’t getting loaded.

Please let me know where I’m going wrong! Thanks.

Answer

You need to read the local file in as a URL so that the WebEngine can find it. For instance, you can find the file as a resouce using

URL url = this.getClass().getResource("/com/cds/gui/webView/main.html");
webEngine.load(url.toString());

Or you can load the actual String path into a File object and use it to get the String URL.

File f = new File("full\path\to\webView\main.html");
webEngine.load(f.toURI().toString());

Hope this helps!

Categories
discuss

file input – accept image from camera or gallery on android

I have Form in my website that accepts a file input. the code for the input is here:

<input type="file" accept="image/*" capture/>

When I run this on my note 4 with google chrome for android I get to choose only Camera apps to add the image from. I cannot choose to use image from gallery or photos.

In IPhone with Safari it works perfect. it allows me to choose from gallery or camera. what not in google chrome for android? what am i missing ?

Answer

If you are using Android 4.4 (Kit Kat) then this is a known issue: Issue 62220

You can follow the suggested work arounds: HTML file input in android webview (android 4.4, kitkat)

Source: stackoverflow
Text is available under the Creative Commons Attribution-ShareAlike License; additional terms may apply. By using this site, you agree to the Privacy Policy, and Copyright Policy. Content is available under CC BY-SA 3.0 unless otherwise noted. The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 © No Copyrights, All Questions are retrived from public domain..