Rectangle 27 7

I started using Sequelize in Express.js app. Soon enough ran into issues of the nature you're describing. Maybe I did not quite understand Sequelize, but to me doing things more than just selecting from one table wasn't really convenient. And where ordinarily you would use select from two or more tables, or a union in pure SQL, you would have to run separate queries, and with the async nature of Node it's just added complexity.

Therefore I moved away from using Sequelize. Moreover I am switching from using ANY data fetching from DB in the models. In my opinion it is better to abstract getting data completely. And reasons are - imagine that you don't just use MySQL (in my case, I use MySQL and MongoDB side by side), but you can get your data from any data provider and any transport method, e.g. SQL, no-SQL, filesystem, external API, FTP, SSH etc. If you tried to do all of it in the models, you would eventually create complex and hard to understand code that would be hard to upgrade and debug.

Now what you want to do is to have models get data from a layer that knows where and how to get it, but your models only use API methods, e.g. fetch, save, delete etc. And inside this layer you have specific implementations for specific data providers. E.g. you can request certain data from a PHP file on a local machine or from Facebook API or from Amazon AWS or from remote HTML document, etc.

These are valid points, but I would rather avoid reimplementing fetch, save, delete etc. outside of Sequelize given that the framework already provides the means. It is nicer, but less convenient to have a separate fetching layer. At the same time, you could probably add a fetching abstraction layer around Sequelize but then the solution is more complicated, for an arguable win.

node.js - How to organize a node app that uses sequelize? - Stack Over...

node.js express sequelize.js
Rectangle 27 115

Simpler with Node.js

JavaScript uses prototypes and does't have classes (or methods for that matter) like Object Oriented languages. A JavaScript developer need to think in JavaScript.

Unlike many object-oriented languages, there is no distinction between a function definition and a method definition. Rather, the distinction occurs during function calling; when a function is called as a method of an object, the function's local this keyword is bound to that object for that invocation.

var MyObject = (function () {

    // Constructor
    function MyObject (foo) {
        this._foo = foo;
    }

    function privateFun (prefix) {
        return prefix + this._foo;
    }

    MyObject.prototype.publicFun = function () {
        return privateFun.call(this, '>>');
    }

    return MyObject;
})();


var myObject = new MyObject('bar');
myObject.publicFun();      // Returns '>>bar'
myObject.privateFun('>>'); // ReferenceError: private is not defined

The call function allows us to call the private function with the appropriate context (this).

If you are using node.js, you don't need the IIFE because you can take advantage of the module loading system:

function MyObject (foo) {
    this._foo = foo;
}

function privateFun (prefix) {
    return prefix + this._foo;
}

MyObject.prototype.publicFun = function () {
    return privateFun.call(this, '>>');
}

exports.MyObject = MyObject;
var MyObject = require('./MyObject').MyObject;

var myObject = new MyObject('bar');
myObject.publicFun();      // Returns '>>bar'
myObject.privateFun('>>'); // ReferenceError: private is not defined
::
export default class MyObject {
  constructor (foo) {
    this._foo = foo;
  }

  publicFun () {
    return this::privateFun('>>');
  }
}

function privateFun (prefix) {
  return prefix + this._foo;
}
import MyObject from './MyObject';

let myObject = new MyObject('bar');
myObject.publicFun();      // Returns '>>bar'
myObject.privateFun('>>'); // TypeError: myObject.privateFun is not a function

This is the best answer. The benefits of private methods, no junk.

.call

@janje Huh? That's the point of the question, there is no private f() in javascript (not at the moment).

@YvesM. The point of the question is choosing the best pattern that simulates it.

@changed what is the best compromise to have hidden functions (un-callable from outside), nice sintax (no .call) and small memory (no functions on the instance) ? Does that even exist ?

oop - JavaScript private methods - Stack Overflow

javascript oop private-methods
Rectangle 27 111

Simpler with Node.js

JavaScript uses prototypes and does't have classes (or methods for that matter) like Object Oriented languages. A JavaScript developer need to think in JavaScript.

Unlike many object-oriented languages, there is no distinction between a function definition and a method definition. Rather, the distinction occurs during function calling; when a function is called as a method of an object, the function's local this keyword is bound to that object for that invocation.

var MyObject = (function () {

    // Constructor
    function MyObject (foo) {
        this._foo = foo;
    }

    function privateFun (prefix) {
        return prefix + this._foo;
    }

    MyObject.prototype.publicFun = function () {
        return privateFun.call(this, '>>');
    }

    return MyObject;
})();


var myObject = new MyObject('bar');
myObject.publicFun();      // Returns '>>bar'
myObject.privateFun('>>'); // ReferenceError: private is not defined

The call function allows us to call the private function with the appropriate context (this).

If you are using node.js, you don't need the IIFE because you can take advantage of the module loading system:

function MyObject (foo) {
    this._foo = foo;
}

function privateFun (prefix) {
    return prefix + this._foo;
}

MyObject.prototype.publicFun = function () {
    return privateFun.call(this, '>>');
}

exports.MyObject = MyObject;
var MyObject = require('./MyObject').MyObject;

var myObject = new MyObject('bar');
myObject.publicFun();      // Returns '>>bar'
myObject.privateFun('>>'); // ReferenceError: private is not defined
::
export default class MyObject {
  constructor (foo) {
    this._foo = foo;
  }

  publicFun () {
    return this::privateFun('>>');
  }
}

function privateFun (prefix) {
  return prefix + this._foo;
}
import MyObject from './MyObject';

let myObject = new MyObject('bar');
myObject.publicFun();      // Returns '>>bar'
myObject.privateFun('>>'); // TypeError: myObject.privateFun is not a function

This is the best answer. The benefits of private methods, no junk.

.call

@janje ? What's the problem with .call ? btw you can move from ES5 and use the :: bind operator (think about using babel)

@janje Huh? That's the point of the question, there is no private f() in javascript (not at the moment).

@YvesM. The point of the question is choosing the best pattern that simulates it.

oop - JavaScript private methods - Stack Overflow

javascript oop private-methods
Rectangle 27 231

Warning for users of Tomcat 7 and below

There are subtle differences as to how the fileName you are passing is interpreted. Basically, you have 2 different methods: ClassLoader.getResourceAsStream() and Class.getResourceAsStream(). These two methods will locate the resource differently.

In Class.getResourceAsStream(path), the path is interpreted as a path local to the package of the class you are calling it from. For example calling, String.getResourceAsStream("myfile.txt") will look for a file in your classpath at the following location: "java/lang/myfile.txt". If your path starts with a /, then it will be considered an absolute path, and will start searching from the root of the classpath. So calling String.getResourceAsStream("/myfile.txt") will look at the following location in your class path ./myfile.txt.

String.getClassLoader().getResourceAsStream("/myfile.txt")
./myfile.txt

Everytime I mention a location in this post, it could be a location in your filesystem itself, or inside the corresponding jar file, depending on the Class and/or ClassLoader you are loading the resource from.

Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName)
this.getClass().getClassLoader().getResourceAsStream(fileName)
this.getClass().getResourceAsStream()

Read this article for more detailed information about that particular problem.

One of the answers to this question states that my explanation seems to be incorrect for Tomcat 7. I've tried to look around to see why that would be the case.

So I've looked at the source code of Tomcat's WebAppClassLoader for several versions of Tomcat. The implementation of findResource(String name) (which is utimately responsible for producing the URL to the requested resource) is virtually identical in Tomcat 6 and Tomcat 7, but is different in Tomcat 8.

In versions 6 and 7, the implementation does not attempt to normalize the resource name. This means that in these versions, classLoader.getResourceAsStream("/resource.txt") may not produce the same result as classLoader.getResourceAsStream("resource.txt") event though it should (since that what the Javadoc specifies). [source code]

In version 8 though, the resource name is normalized to guarantee that the absolute version of the resource name is the one that is used. Therefore, in Tomcat 8, the two calls described above should always return the same result. [source code]

ClassLoader.getResourceAsStream()
Class.getResourceAsStream()
class.getResourceAsStream("/resource.txt")
classLoader.getResourceAsStream("resource.txt")
getClass().getResourceAsStream("/myfile.txt")
getClassLoader().getResourceAsStream("/myfile.txt")

@BrianGordon: They don't behave differenty. Actually, the javadoc for Class.getResourceAsStream(String) says the following thing: "This method delegates to this object's class loader.", and then gives a bunch of rules on how it converts a relative path to an absolute path before delegating to the classloader.

@LordOfThePigs Look at the actual source. Class.getResourceAsStream strips off the leading forward slash if you provide an absolute path.

@BrianGordon: Which makes it behave exactly the same as ClassLoader.getResourceAsStream() since the latter interprets all paths as absolute, whether they start with a leading slash or not. So as long as you path is absolute, both methods behave identically. If your path is relative, then the behavior is different.

java - Different ways of loading a file as an InputStream - Stack Over...

java inputstream
Rectangle 27 231

Warning for users of Tomcat 7 and below

There are subtle differences as to how the fileName you are passing is interpreted. Basically, you have 2 different methods: ClassLoader.getResourceAsStream() and Class.getResourceAsStream(). These two methods will locate the resource differently.

In Class.getResourceAsStream(path), the path is interpreted as a path local to the package of the class you are calling it from. For example calling, String.getResourceAsStream("myfile.txt") will look for a file in your classpath at the following location: "java/lang/myfile.txt". If your path starts with a /, then it will be considered an absolute path, and will start searching from the root of the classpath. So calling String.getResourceAsStream("/myfile.txt") will look at the following location in your class path ./myfile.txt.

String.getClassLoader().getResourceAsStream("/myfile.txt")
./myfile.txt

Everytime I mention a location in this post, it could be a location in your filesystem itself, or inside the corresponding jar file, depending on the Class and/or ClassLoader you are loading the resource from.

Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName)
this.getClass().getClassLoader().getResourceAsStream(fileName)
this.getClass().getResourceAsStream()

Read this article for more detailed information about that particular problem.

One of the answers to this question states that my explanation seems to be incorrect for Tomcat 7. I've tried to look around to see why that would be the case.

So I've looked at the source code of Tomcat's WebAppClassLoader for several versions of Tomcat. The implementation of findResource(String name) (which is utimately responsible for producing the URL to the requested resource) is virtually identical in Tomcat 6 and Tomcat 7, but is different in Tomcat 8.

In versions 6 and 7, the implementation does not attempt to normalize the resource name. This means that in these versions, classLoader.getResourceAsStream("/resource.txt") may not produce the same result as classLoader.getResourceAsStream("resource.txt") event though it should (since that what the Javadoc specifies). [source code]

In version 8 though, the resource name is normalized to guarantee that the absolute version of the resource name is the one that is used. Therefore, in Tomcat 8, the two calls described above should always return the same result. [source code]

ClassLoader.getResourceAsStream()
Class.getResourceAsStream()
class.getResourceAsStream("/resource.txt")
classLoader.getResourceAsStream("resource.txt")
getClass().getResourceAsStream("/myfile.txt")
getClassLoader().getResourceAsStream("/myfile.txt")

@BrianGordon: They don't behave differenty. Actually, the javadoc for Class.getResourceAsStream(String) says the following thing: "This method delegates to this object's class loader.", and then gives a bunch of rules on how it converts a relative path to an absolute path before delegating to the classloader.

@LordOfThePigs Look at the actual source. Class.getResourceAsStream strips off the leading forward slash if you provide an absolute path.

@BrianGordon: Which makes it behave exactly the same as ClassLoader.getResourceAsStream() since the latter interprets all paths as absolute, whether they start with a leading slash or not. So as long as you path is absolute, both methods behave identically. If your path is relative, then the behavior is different.

java - Different ways of loading a file as an InputStream - Stack Over...

java inputstream
Rectangle 27 18

Passing method arguments is supported since EL 2.2 which is part of Servlet 3.0. So if your webapp runs on a Servlet 3.0 compatible container (Tomcat 7, Glassfish 3, etc) with a web.xml declared conform Servlet 3.0 spec (which is likely true as you're using JSF 2.1 which in turn implicitly requires Servlet 3.0), then you will be able to pass method arguments to bean action methods in the following form:

public void submit(Long id) {
    // ...
}

You can even pass fullworthy objects along like as:

<h:commandButton value="Submit" action="#{bean.submit(item)}" />

with

public void submit(Item item) {
    // ...
}

If you were targeting a Servlet 2.5 container, then you could achieve the same by replacing the EL implementation by for example JBoss EL which supports the same construct. See also Invoke direct methods or methods with arguments / variables / parameters in EL.

is this also possible inside tags or components? When I pass a bean to the component/tag I call the method on the attribute that holds the bean, e.g. action="#{myBean['actionToCall']}". From the top of my head I wouldn't know how to pass a parameter in brackets syntax other than setting it with a f:setPropertyActionListener, and we need brackets over dots in this case, right?

@Louise: just use action="#{myBean['actionToCall'](someParam)}". Note that this syntax had a bug in older Tomcat and Glassfish versions. Only since Tomcat 7.0.22 and Glassfish 3.1.2 it should work properly.

Where this "item" (or "item.id") comes from? Can it be something like the id of the selected p:tab in a p:tabView (primefaces)?

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

primefaces - Calling bean methods with arguments from JSF pages - Stac...

jsf primefaces
Rectangle 27 18

Passing method arguments is supported since EL 2.2 which is part of Servlet 3.0. So if your webapp runs on a Servlet 3.0 compatible container (Tomcat 7, Glassfish 3, etc) with a web.xml declared conform Servlet 3.0 spec (which is likely true as you're using JSF 2.1 which in turn implicitly requires Servlet 3.0), then you will be able to pass method arguments to bean action methods in the following form:

public void submit(Long id) {
    // ...
}

You can even pass fullworthy objects along like as:

<h:commandButton value="Submit" action="#{bean.submit(item)}" />

with

public void submit(Item item) {
    // ...
}

If you were targeting a Servlet 2.5 container, then you could achieve the same by replacing the EL implementation by for example JBoss EL which supports the same construct. See also Invoke direct methods or methods with arguments / variables / parameters in EL.

is this also possible inside tags or components? When I pass a bean to the component/tag I call the method on the attribute that holds the bean, e.g. action="#{myBean['actionToCall']}". From the top of my head I wouldn't know how to pass a parameter in brackets syntax other than setting it with a f:setPropertyActionListener, and we need brackets over dots in this case, right?

@Louise: just use action="#{myBean['actionToCall'](someParam)}". Note that this syntax had a bug in older Tomcat and Glassfish versions. Only since Tomcat 7.0.22 and Glassfish 3.1.2 it should work properly.

Where this "item" (or "item.id") comes from? Can it be something like the id of the selected p:tab in a p:tabView (primefaces)?

primefaces - Calling bean methods with arguments from JSF pages - Stac...

jsf primefaces
Rectangle 27 82

Windows filesystems have no problem using either forward or backward slashes as path separators (this has been the case since back in the DOS days). The only real issue is that Windows command-line processors (or, more specifically, Windows-native command-line utilities) tend to interpret forward slashes as option specifiers rather than path components. Therefore, you need a backslashed path if you need to pass a path to a Windows command run as a subprocess. Also, Windows API calls (and methods from higher-level languages that call the Windows API) that return paths will use backslashes, so even if you aren't passing them to subprocesses, you'll need to normalize them.

Forward slashes also break UNC paths.

Do you need to use path.join in Node.js? - Stack Overflow

node.js path
Rectangle 27 35

Syntax of Lambda Expressions

In Java 8, you can now pass a method more easily using Lambda Expressions. First, some background. A functional interface is an interface that has one and only one abstract method, although it can contain any number of default methods (new in Java 8) and static methods. A lambda expression can quickly implement the abstract method, without all the unnecessary syntax needed if you don't use a lambda expression.

obj.aMethod(new AFunctionalInterface() {
    @Override
    public boolean anotherMethod(int i)
    {
        return i == 982
    }
});
obj.aMethod(i -> i == 982);

A lambda expression consists of the following:

A comma-separated list of formal parameters enclosed in parentheses. The CheckPerson.test method contains one parameter, p, which represents an instance of the Person class.Note: You can omit the data type of the parameters in a lambda expression. In addition, you can omit the parentheses if there is only one parameter. For example, the following lambda expression is also valid:

p -> p.getGender() == Person.Sex.MALE 
    && p.getAge() >= 18
    && p.getAge() <= 25
->

A body, which consists of a single expression or a statement block. This example uses the following expression:

p.getGender() == Person.Sex.MALE 
    && p.getAge() >= 18
    && p.getAge() <= 25

If you specify a single expression, then the Java runtime evaluates the expression and then returns its value. Alternatively, you can use a return statement:

p -> {
    return p.getGender() == Person.Sex.MALE
        && p.getAge() >= 18
        && p.getAge() <= 25;
}

A return statement is not an expression; in a lambda expression, you must enclose statements in braces ({}). However, you do not have to enclose a void method invocation in braces. For example, the following is a valid lambda expression:

email -> System.out.println(email)

Note that a lambda expression looks a lot like a method declaration; you can consider lambda expressions as anonymous methodsmethods without a name.

Here is how you can "pass a method" using a lambda expression:

interface I {
    public void myMethod(Component component);
}

class A {
    public void changeColor(Component component) {
        // code here
    }

    public void changeSize(Component component) {
        // code here
    }
}

class B {
    public void setAllComponents(Component[] myComponentArray, I myMethodsInterface) {
        for(Component leaf : myComponentArray) {
            if(leaf instanceof Container) { // recursive call if Container
                Container node = (Container)leaf;
                setAllComponents(node.getComponents(), myMethodInterface);
            } // end if node
            myMethodsInterface.myMethod(leaf);
        } // end looping through components
    }
}

class C {
    A a = new A();
    B b = new B();

    public C() {
        b.setAllComponents(this.getComponents(), component -> a.changeColor(component));
        b.setAllComponents(this.getComponents(), component -> a.changeSize(component));
    }
}

@Serob_b Nope. Unless you want to pass it as a method reference (see :: operator), it doesn't matter what A is. a.changeThing(component) can be changed to any statement or code block you want, as long as it returns void.

interface - Java Pass Method as Parameter - Stack Overflow

java interface
Rectangle 27 35

Syntax of Lambda Expressions

In Java 8, you can now pass a method more easily using Lambda Expressions. First, some background. A functional interface is an interface that has one and only one abstract method, although it can contain any number of default methods (new in Java 8) and static methods. A lambda expression can quickly implement the abstract method, without all the unnecessary syntax needed if you don't use a lambda expression.

obj.aMethod(new AFunctionalInterface() {
    @Override
    public boolean anotherMethod(int i)
    {
        return i == 982
    }
});
obj.aMethod(i -> i == 982);

A lambda expression consists of the following:

A comma-separated list of formal parameters enclosed in parentheses. The CheckPerson.test method contains one parameter, p, which represents an instance of the Person class.Note: You can omit the data type of the parameters in a lambda expression. In addition, you can omit the parentheses if there is only one parameter. For example, the following lambda expression is also valid:

p -> p.getGender() == Person.Sex.MALE 
    && p.getAge() >= 18
    && p.getAge() <= 25
->

A body, which consists of a single expression or a statement block. This example uses the following expression:

p.getGender() == Person.Sex.MALE 
    && p.getAge() >= 18
    && p.getAge() <= 25

If you specify a single expression, then the Java runtime evaluates the expression and then returns its value. Alternatively, you can use a return statement:

p -> {
    return p.getGender() == Person.Sex.MALE
        && p.getAge() >= 18
        && p.getAge() <= 25;
}

A return statement is not an expression; in a lambda expression, you must enclose statements in braces ({}). However, you do not have to enclose a void method invocation in braces. For example, the following is a valid lambda expression:

email -> System.out.println(email)

Note that a lambda expression looks a lot like a method declaration; you can consider lambda expressions as anonymous methodsmethods without a name.

Here is how you can "pass a method" using a lambda expression:

interface I {
    public void myMethod(Component component);
}

class A {
    public void changeColor(Component component) {
        // code here
    }

    public void changeSize(Component component) {
        // code here
    }
}

class B {
    public void setAllComponents(Component[] myComponentArray, I myMethodsInterface) {
        for(Component leaf : myComponentArray) {
            if(leaf instanceof Container) { // recursive call if Container
                Container node = (Container)leaf;
                setAllComponents(node.getComponents(), myMethodInterface);
            } // end if node
            myMethodsInterface.myMethod(leaf);
        } // end looping through components
    }
}

class C {
    A a = new A();
    B b = new B();

    public C() {
        b.setAllComponents(this.getComponents(), component -> a.changeColor(component));
        b.setAllComponents(this.getComponents(), component -> a.changeSize(component));
    }
}

@Serob_b Nope. Unless you want to pass it as a method reference (see :: operator), it doesn't matter what A is. a.changeThing(component) can be changed to any statement or code block you want, as long as it returns void.

interface - Java Pass Method as Parameter - Stack Overflow

java interface
Rectangle 27 7

Use message passing(MDN)(send data after content script is injected)

There are five general ways to pass data to a content script injected with tabs.executeScript()(MDN):

chrome.storage.local
  • Inject code prior to your script which sets a variable with the data (see detailed discussion for possible security issue).
  • Set a cookie for the domain in which the content script is being injected. This method can also be used to pass data to manifest.json content scripts which are injected at document_start, without the need for the content script to perform an asynchronous request.
  • Use chrome.storage.onChanged(MDN) in your content script to listen for the background script to set a value using chrome.storage.local.set()(MDN).

Using this method maintains the execution paradigm you are using of injecting a script that performs a function and then exits. It also does not have the potential security issue of using a dynamic value to build executing code, which is done in the second option below.

  • Store the data using chrome.storage.local.set()(MDN).
chrome.storage.local.set()
  • Read the data from chrome.storage.local.get()(MDN).
  • Invalidate the data in storage.local (e.g. remove the key with: chrome.storage.local.remove()(MDN)).
chrome.storage.local.get('updateTextTo', function (items) {
    assignTextToTextareas(items.updateTextTo);
    chrome.storage.local.remove('updateTextTo');
});
function assignTextToTextareas(newText){
    if (typeof newText === 'string') {
        Array.from(document.querySelectorAll('textarea.comments')).forEach(el => {
            el.value = newText;
        });
    }
}

Prior to executing your script, you can inject some code that sets a variable in the content script context which your primary script can then use:

The following uses "'" + JSON.stringify().replace(/\\/g,'\\\\').replace(/'/g,"\\'") + "'" to encode the data into text which will be proper JSON when interpreted as code, prior to putting it in the code string. The .replace() methods are needed to A) have the text correctly interpreted as a string when used as code, and B) quote any ' which exist in the data. It then uses JSON.parse() to return the data to a string in your content script. While this encoding is not strictly required, it is a good idea as you don't know the content of the value which you are going to send to the content script. This value could easily be something that would corrupt the code you are injecting (i.e. The user may be using ' and/or " in the text they entered). If you do not, in some way, escape the value, there is a security hole which could result in arbitrary code being executed.

  • Inject a simple piece of code that sets a variable to contain the data.
  • In the callback for chrome.tabs.executeScript()(MDN), call tabs.executeScript() to inject your script (Note: tabs.executeScript() will execute scripts in the order in which you call tabs.executeScript(), as long as they have the same value for runAt. Thus, waiting for the callback of the small code is not strictly required).
  • Make the changes to the DOM using the data stored in the variable
if (typeof newText === 'string') {
    Array.from(document.querySelectorAll('textarea.comments')).forEach(el => {
        el.value = newText;
    });
}

This requires your content script code to install a listener for a message sent by the popup, or perhaps the background script (if the interaction with the UI causes the popup to close). It is a bit more complex.

tabs.query()
tabs.executeScript()
  • In the callback for tabs.executeScript(), use tabs.sendMessage()(MDN)(which requires knowing the tabId), to send the data as a message.
var updateTextTo = document.getElementById('comments').value;
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
    chrome.tabs.executeScript(tabs[0].id, {
        file: "content_script3.js"
    }, function(){
        chrome.tabs.sendMessage(tabs[0].id,{
            updateTextTo: updateTextTo
        });
    });
});
  • Add a listener using chrome.runtime.onMessage.addListener()(MDN).
  • Exit your primary code, leaving the listener active. You could return a success indicator, if you choose.
  • Make the changes to the DOM.
runtime.onMessage

#3.2 is optional. You could keep your code active waiting for another message, but that would change the paradigm you are using to one where you load your code and it stays resident waiting for messages to initiate actions.

chrome.runtime.onMessage.addListener(assignTextToTextareas);
function assignTextToTextareas(message){
    newText = message.updateTextTo;
    if (typeof newText === 'string') {
        Array.from(document.querySelectorAll('textarea.comments')).forEach(el => {
            el.value = newText;
        });
    }
    chrome.runtime.onMessage.removeListener(assignTextToTextareas);  //optional
}

Note 1: Using Array.from() is fine if you are not doing it many times and are using a browser version which has it (Chrome >= version 45, Firefox >= 32). In Chrome and Firefox, Array.from() is slow compared to other methods of getting an array from a NodeList. For a faster, more compatible conversion to an Array, you could use the asArray() code in this answer. The second version of asArray() provided in that answer is also more robust.

Note 2: If you are willing to limit your code to Chrome version >= 51 or Firefox version >= 50, Chrome has a forEach() method for NodeLists as of v51. Thus, you don't need to convert to an array. Obviously, you don't need to convert to an Array if you use a different type of loop.

Note 3: While I have previously used this method (injecting a script with the variable value) in my own code, I was reminded that I should have included it here when reading this answer.

You sure about "will execute scripts in the order in which you cal.."? Isn't the order undefined?

@Pacerier, All of my testing (other project, not just for this answer) showed (same runAt) scripts are injected in the order tabs.executeScript() is called (both Chrome & Firefox). I don't recall if I looked through the source code on both to verify. An important aspect of this is that injected scripts come from within your extension, not network resources (where most async delay would be). You're correct that it's not guaranteed in the documentation, which is why I wrote it such that it does actually wait for the tabs.executeScript() callback to inject the second, non-code: script.

@Pacerier, Most reasonable ways to implement such code might not guarantee that the injection occurs in the order tabs.executeScript() is executed, but would make it unlikely that it would not be in that order. For example: tabs.executeScript() probably enters a message instructing the injection in a message queue to be sent to the correct process handling the content. Once received in that process, it would enter a queue for injection (separate queue's per runAt, or at least organized by runAt), or be immediately processed (e.g. for code: that is immediately available). etc.

@Pacerier, In this instance, the code: script is immediately available (does not even need to be fetched from within your extension (i.e. disk, or RAM cache)). This means that it is even more likely to be injected before the other script. However, the testing I did indicated that even for multiple (same runAt) scripts fetched from within the extension, the scripts were injected in the order tabs.executeScript() is called. Again, it's not guaranteed, but it works at least 99%+ of the time. But, that does not mean you should not wait for the callback, when you have a hard dependency.

javascript - Pass a parameter to a content script injected using chrom...

javascript google-chrome-extension
Rectangle 27 30

Found the solution! It seems that the public API of gm does not provide any proper methods for what I needed. The solution was to use not-so-public .in method which makes possible to insert custom GraphicsMagick arguments.

The following code takes in four 256x256 images, merges them to 2x2 grid on 512x512 canvas, halves the size to 256x256 using fast linear interpolation and saves the result to output.jpg.

var gm = require('gm');

// a b c d  ->  ab
//              cd
gm()
    .in('-page', '+0+0')  // Custom place for each of the images
    .in('a.jpg')
    .in('-page', '+256+0')
    .in('b.jpg')
    .in('-page', '+0+256')
    .in('c.jpg')
    .in('-page', '+256+256')
    .in('d.jpg')
    .minify()  // Halves the size, 512x512 -> 256x256
    .mosaic()  // Merges the images as a matrix
    .write('output.jpg', function (err) {
        if (err) console.log(err);
    });

Tile four images together using Node.js and GraphicsMagick - Stack Ove...

node.js graphicsmagick
Rectangle 27 30

Found the solution! It seems that the public API of gm does not provide any proper methods for what I needed. The solution was to use not-so-public .in method which makes possible to insert custom GraphicsMagick arguments.

The following code takes in four 256x256 images, merges them to 2x2 grid on 512x512 canvas, halves the size to 256x256 using fast linear interpolation and saves the result to output.jpg.

var gm = require('gm');

// a b c d  ->  ab
//              cd
gm()
    .in('-page', '+0+0')  // Custom place for each of the images
    .in('a.jpg')
    .in('-page', '+256+0')
    .in('b.jpg')
    .in('-page', '+0+256')
    .in('c.jpg')
    .in('-page', '+256+256')
    .in('d.jpg')
    .minify()  // Halves the size, 512x512 -> 256x256
    .mosaic()  // Merges the images as a matrix
    .write('output.jpg', function (err) {
        if (err) console.log(err);
    });

Tile four images together using Node.js and GraphicsMagick - Stack Ove...

node.js graphicsmagick
Rectangle 27 5

The Django template engine doesn't support passing arguments to methods like that. To accomplish the same thing, try using the date filter:

(Edited: fixed the syntax for the date string, because I'm stupid.)

{{ report.date|date:"f A" }}

Python - Google App Engine - Methods in Django template - Stack Overfl...

python google-app-engine methods django-templates
Rectangle 27 4

Use message passing(MDN)(send data after content script is injected)

There are four general ways to pass data to a content script injected with tabs.executeScript()(MDN):

chrome.storage.local
  • Inject code prior to your script which sets a variable with the data (see detailed discussion for possible security issue).
  • Use chrome.storage.onChanged(MDN) in your content script to listen for the background script to set a value using chrome.storage.local.set()(MDN).

Using this method maintains the execution paradigm you are using of injecting a script that performs a function and then exits. It also does not have the potential security issue of using a dynamic value to build executing code, which is done in the second option below.

  • Store the data using chrome.storage.local.set()(MDN).
chrome.storage.local.set()
  • Read the data from chrome.storage.local.get()(MDN).
  • Invalidate the data in storage.local (e.g. remove the key with: chrome.storage.local.remove()(MDN)).
chrome.storage.local.get('updateTextTo', function (items) {
    assignTextToTextareas(items.updateTextTo);
    chrome.storage.local.remove('updateTextTo');
});
function assignTextToTextareas(newText){
    if (typeof newText === 'string') {
        Array.from(document.querySelectorAll('textarea.comments')).forEach(el => {
            el.value = newText;
        });
    }
}

Prior to executing your script, you can inject some code that sets a variable in the content script context which your primary script can then use:

The following uses "'" + JSON.stringify().replace(/\\/g,'\\\\').replace(/'/g,"\\'") + "'" to encode the data into text which will be proper JSON when interpreted as code, prior to putting it in the code string. The .replace() methods are needed to A) have the text correctly interpreted as a string when used as code, and B) quote any ' which exist in the data. It then uses JSON.parse() to return the data to a string in your content script. While this encoding is not strictly required, it is a good idea as you don't know the content of the value which you are going to send to the content script. This value could easily be something that would corrupt the code you are injecting (i.e. The user may be using ' and/or " in the text they entered). If you do not, in some way, escape the value, there is a security hole which could result in arbitrary code being executed.

  • Inject a simple piece of code that sets a variable to contain the data.
  • In the callback for chrome.tabs.executeScript()(MDN), call tabs.executeScript() to inject your script (Note: tabs.executeScript() will execute scripts in the order in which you call tabs.executeScript(), as long as they have the same value for runAt. Thus, waiting for the callback of the small code is not strictly required).
  • Make the changes to the DOM using the data stored in the variable
if (typeof newText === 'string') {
    Array.from(document.querySelectorAll('textarea.comments')).forEach(el => {
        el.value = newText;
    });
}

This requires your content script code to install a listener for a message sent by the popup, or perhaps the background script (if the interaction with the UI causes the popup to close). It is a bit more complex.

tabs.query()
tabs.executeScript()
  • In the callback for tabs.executeScript(), use tabs.sendMessage()(MDN)(which requires knowing the tabId), to send the data as a message.
var updateTextTo = document.getElementById('comments').value;
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
    chrome.tabs.executeScript(tabs[0].id, {
        file: "content_script3.js"
    }, function(){
        chrome.tabs.sendMessage(tabs[0].id,{
            updateTextTo: updateTextTo
        });
    });
});
  • Add a listener using chrome.runtime.onMessage.addListener()(MDN).
  • Exit your primary code, leaving the listener active. You could return a success indicator, if you choose.
  • Make the changes to the DOM.
runtime.onMessage

#3.2 is optional. You could keep your code active waiting for another message, but that would change the paradigm you are using to one where you load your code and it stays resident waiting for messages to initiate actions.

chrome.runtime.onMessage.addListener(assignTextToTextareas);
function assignTextToTextareas(message){
    newText = message.updateTextTo;
    if (typeof newText === 'string') {
        Array.from(document.querySelectorAll('textarea.comments')).forEach(el => {
            el.value = newText;
        });
    }
    chrome.runtime.onMessage.removeListener(assignTextToTextareas);  //optional
}

Note 1: Using Array.from() is fine if you are not doing it many times and are using a browser version which has it (Chrome >= version 45, Firefox >= 32). In Chrome and Firefox, Array.from() is slow compared to other methods of getting an array from a NodeList. For a faster, more compatible conversion to an Array, you could use the asArray() code in this answer. The second version of asArray() provided in that answer is also more robust.

Note 2: If you are willing to limit your code to Chrome version >= 51 or Firefox version >= 50, Chrome has a forEach() method for NodeLists as of v51. Thus, you don't need to convert to an array. Obviously, you don't need to convert to an Array if you use a different type of loop.

Note 3: While I have previously used this method (injecting a script with the variable value) in my own code, I was reminded that I should have included it here when reading this answer.

You sure about "will execute scripts in the order in which you cal.."? Isn't the order undefined?

@Pacerier, All of my testing (other project, not just for this answer) showed (same runAt) scripts are injected in the order tabs.executeScript() is called (both Chrome & Firefox). I don't recall if I looked through the source code on both to verify. An important aspect of this is that injected scripts come from within your extension, not network resources (where most async delay would be). You're correct that it's not guaranteed in the documentation, which is why I wrote it such that it does actually wait for the tabs.executeScript() callback to inject the second, non-code: script.

@Pacerier, Most reasonable ways to implement such code might not guarantee that the injection occurs in the order tabs.executeScript() is executed, but would make it unlikely that it would not be in that order. For example: tabs.executeScript() probably enters a message instructing the injection in a message queue to be sent to the correct process handling the content. Once received in that process, it would enter a queue for injection (separate queue's per runAt, or at least organized by runAt), or be immediately processed (e.g. for code: that is immediately available). etc.

@Pacerier, In this instance, the code: script is immediately available (does not even need to be fetched from within your extension (i.e. disk, or RAM cache)). This means that it is even more likely to be injected before the other script. However, the testing I did indicated that even for multiple (same runAt) scripts fetched from within the extension, the scripts were injected in the order tabs.executeScript() is called. Again, it's not guaranteed, but it works at least 99%+ of the time. But, that does not mean you should not wait for the callback, when you have a hard dependency.

javascript - Pass a parameter to a content script injected using chrom...

javascript google-chrome-extension
Rectangle 27 9

An example of passing contextual data using SessionContext can be found here

The last (and most interesting part) would be how to get the user credentials on the EJB layer. If you're saying about WebServices endpoint than I guess you need to provide some kind of boundary class or specify a methods which will take some sessionId for each call.

If it's about propagating HttpSession data from the Servlet to the EJB... It might be a long shot but I would think of using the CDI. Your Servlet might use a @SessionScoped bean which holds the user credentials and you inject the same @SessionScoped bean inside the interceptor.

I'm not sure if it's possible at all (injecting CDI beans in the interceptors or sharing @SessionScoped between Servlets and EJB's layers).

(Had to split my reply in 3...) Regarding 2, that is a good idea especially if I can pass context information without a method argument. Otherwise, I would have to use reflection on the argument list to find which one contains the auth info.

Regarding 1, there is one problem with interceptors though and a method signature like removeTransaction(AuthenticationInfo authInfo, long personId, long transactionId). In this case, the authorization is dependant on personId but the interceptor does not obtain argument names but only argument types. Therefore, its only way to know whether to use argument #2 or #3 is to add meta-data somewhere which can get out of sync with the method declaration. This is not the case if the authorization is done as a method call in the body of removeTransaction.

As for CDI, I dont currently use it and my perception of its lack of maturity, especially with regards to integration with my web framework (Wicket), doesnt make me want to make the switch. I might be wrong however. Nevertheless, your idea is certainly an interesting one however. It allowed me to find stackoverflow.com/questions/2607019/ which gives some more insight.

AD 2. yes - AFAIR - it can be added without specyfing additional method parameters. AD 1. well, if you're afraid about that I can think of using custom annotation like @AuthorizationData; than in interceptor you could use InvocationContext#getMethod()#getParameterAnnotations(), then search for the parameter which has @AuthorizationData assigned and this will be the number of the parameter you want to get.

@Bernie, I've added link to the page where I've shown how contextData could be used. Hope it'll be of any help to you.

security - Adding custom context information to EJB method calls - Sta...

security authentication java-ee ejb-3.0 java-ee-6
Rectangle 27 638

If you're just passing objects around then Parcelable was designed for this. It requires a little more effort to use than using Java's native serialization, but it's way faster (and I mean way, WAY faster).

From the docs, a simple example for how to implement is:

// simple class that just has one member property as an example
public class MyParcelable implements Parcelable {
    private int mData;

    /* everything below here is for implementing Parcelable */

    // 99.9% of the time you can just ignore this
    @Override
    public int describeContents() {
        return 0;
    }

    // write your object's data to the passed-in Parcel
    @Override
    public void writeToParcel(Parcel out, int flags) {
        out.writeInt(mData);
    }

    // this is used to regenerate your object. All Parcelables must have a CREATOR that implements these two methods
    public static final Parcelable.Creator<MyParcelable> CREATOR = new Parcelable.Creator<MyParcelable>() {
        public MyParcelable createFromParcel(Parcel in) {
            return new MyParcelable(in);
        }

        public MyParcelable[] newArray(int size) {
            return new MyParcelable[size];
        }
    };

    // example constructor that takes a Parcel and gives you an object populated with it's values
    private MyParcelable(Parcel in) {
        mData = in.readInt();
    }
}

Observe that in the case you have more than one field to retrieve from a given Parcel, you must do this in the same order you put them in (that is, in a FIFO approach).

Once you have your objects implement Parcelable it's just a matter of putting them into your Intents with putExtra():

Intent i = new Intent();
i.putExtra("name_of_extra", myParcelableObject);

Then you can pull them back out with getParcelableExtra():

Intent i = getIntent();
MyParcelable myParcelableObject = (MyParcelable) i.getParcelableExtra("name_of_extra");

If your Object Class implements Parcelable and Serializable then make sure you do cast to one of the following:

i.putExtra("parcelable_extra", (Parcelable) myParcelableObject);
i.putExtra("serializable_extra", (Serializable) myParcelableObject);

How would this be implemented where mData is an object (e.g. JSONObject) and not an int?

Why can't just pass the object without all this? We want to pass an object that is already in memory.

@tecnotron its beacuse apps are in different processes, and have separate memory address spaces, you cant just send pointer (reference) to memory block in your process and expect it to be available in another process.

What do i do if i cant make the object's class serializible or Parceable?

@ceklock the reason behind this is as follows: When the activity goes behind and later killed from the memory, and then when user opens it from the recents menu, it has to create the Activity where it left off. It has to be the same UI. The Object is not in the memory in this case. But the intent is.

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

How to send an object from one Android Activity to another using Inten...

android android-intent android-activity
Rectangle 27 8

The standard way of passing/submitting data to the server in the pure Servlets/JSP world (as in your case from the JSP to the servlet) is by using HTML form, i.e. the same way as when using other technologies (ASP.NET, PHP etc). And it doesn't matter whether it is a pure HTML page or JSP page. The recommended/most used method of submitting data from the form to the server is POST.

You also can pass data in the query string that is contained in the request URL after the path (this also happens when instead of POST you use GET method in the form). But that is for the simple cases, like constructing URLs for the pagination etc (you can see the example of constructing URLs with the additional queries here: Composing URL in JSP) Example of passing parameters in the URL:http://example.com/foo?param1=bar&page=100

difference between submitting data using GET and POST methods

So you can configure some servlet to process data sent/submitted from a JSP or HTML etc. It is highly recommended to submit data using POST method and respectively to process the submitted data using the doPost() method in your servlet. You will then get the parameters passed by the client in the request by using one of the following ServletRequest methods:

Another way of exchanging data using Java EE is by storing data as attributes in different scopes. (Following is the excerpt from one of my answers on SO)

You can store some data in all the above scopes by setting the appropriate attribute.

void setAttribute(java.lang.String name,
                  java.lang.Object o)

Stores an attribute in this request. Attributes are reset between requests. This method is most often used in conjunction with RequestDispatcher. ...

So with every new request the previous attributes you have set in request will be lost. After you have set an attribute in a request, you must forward the request to the desired page. If you redirect, this will be a totally NEW request, thus the attributes previously set will be lost. (If you still want use redirection read this: Servlet Redirection to same page with error message)

Those attributes that are set in a HttpSession (in the session scope) will live as long as the session lives and, of course, will be available to only the user to which session belongs.

As for the context attributes they are meant to be available to the whole web application (application scope) and for ALL users, plus they live as long as the web application lives.

Also pay attention to the following issue. You wrote (quote):

I know , We can pass variable from servlet to jsp by using request.setAttribute(key , value) But when I used it to set variable in jsp and again get it by using session.getAttribute(key ) then result is null.

As the users @neel and @Sanchit have noticed, you are setting an attribute in the request object, but trying to get it back from the session. No wonder you are getting null in this case.

@SanjayaPandey You are welcome!

java - Passing variables from JSP to servlet - Stack Overflow

java jsp servlets httprequest
Rectangle 27 6

In order to do this you'll need to tell SWIG to use java.util.Map for the input argument, using %typemap(jstype). You'll also need to supply some code to convert from the Java map type to the C++ std::map type, which SWIG will inject at appropriate points. I've put together a small (compiled, but untested) example to illustrate this:

%module test

%include <std_map.i>
%include <std_string.i>

%typemap(jstype) std::map<std::string, std::string> "java.util.Map<String,String>"
%typemap(javain,pre="    MapType temp$javainput = $javaclassname.convertMap($javainput);",pgcppname="temp$javainput") std::map<std::string, std::string> "$javaclassname.getCPtr(temp$javainput)"
%typemap(javacode) std::map<std::string, std::string> %{
  static $javaclassname convertMap(java.util.Map<String,String> in) {
    $javaclassname out = new $javaclassname();
    for (java.util.Map.Entry<String, String> entry : in.entrySet()) {
      out.set(entry.getKey(), entry.getValue());      
    }
    return out;
  }    
%}

%template(MapType) std::map<std::string, std::string>;

void foo(std::map<std::string, std::string>);

The pgcppname part is making sure that the std::map we pass in doesn't get garbage collected too early. See this example in the SWIG documentation for more details on how that works.

To support returning from std::map from C++ to Java takes quite a bit more work, but is possible. java.util.Map is an interface so we need to adapt the default wrapping of std::map to meet that interface. In practice it's easier to use java.util.AbstractMap and inherit from that although I ended up overriding most of the functions in that anyway. This whole solution is analogous to my answer for std::vector.

There are quite a few moving parts in my final version. I'll present it complete here, with annotated notes:

%module test
%{
#include <cassert>
#include <iostream>
%}

%include <std_map.i>

// 1.
%rename (size_impl) std::map<std::string,std::string>::size;
%rename (isEmpty) std::map<std::string,std::string>::empty;
%include <std_string.i>

%typemap(jstype) std::map<std::string, std::string> "java.util.Map<String,String>"
%typemap(javain,pre="    MapType temp$javainput = $javaclassname.convertMap($javainput);",pgcppname="temp$javainput") std::map<std::string, std::string> "$javaclassname.getCPtr(temp$javainput)"
%typemap(javacode) std::map<std::string, std::string> %{
  static $javaclassname convertMap(Map<String,String> in) {
    // 2.
    if (in instanceof $javaclassname) {
      return ($javaclassname)in;
    }

    $javaclassname out = new $javaclassname();
    for (Map.Entry<String, String> entry : in.entrySet()) {
      out.set(entry.getKey(), entry.getValue());
    }
    return out;
  }

  // 3.
  public Set<Map.Entry<String,String>> entrySet() {
    HashSet<Map.Entry<String,String>> ret = new HashSet<Map.Entry<String,String>>(size());
    String array[] = new String[size()];
    all_keys(array);
    for (String key: array) {
      ret.add(new MapTypeEntry(key,this));
    }
    return ret;
  }

  public Collection<String> values() {
    String array[] = new String[size()];
    all_values(array);
    return new ArrayList<String>(Arrays.asList(array));
  }

  public Set<String> keySet() {
    String array[] = new String[size()];
    all_keys(array);
    return new HashSet<String>(Arrays.asList(array));
  }

  // 4.
  public String remove(Object key) {
    final String ret = get(key);
    remove((String)key);
    return ret;
  }

  public String put(String key, String value) {
    final String ret = has_key(key) ? get(key) : null;
    set(key, value);
    return ret;
  }

  // 5.
  public int size() {
    return (int)size_impl();
  }
%}

// 6.
%typemap(javaimports) std::map<std::string, std::string> "import java.util.*;";
// 7.
%typemap(javabase) std::map<std::string, std::string> "AbstractMap<String, String>";

// 8.
%{
template <typename K, typename V>
struct map_entry {
  const K key;
  map_entry(const K& key, std::map<K,V> *owner) : key(key), m(owner) {
  }
  std::map<K,V> * const m;
};
%}

// 9.
template <typename K, typename V>
struct map_entry {
  const K key;
  %extend {
    V getValue() const {
      return (*$self->m)[$self->key];
    }

    V setValue(const V& n) const {
      const V old = (*$self->m)[$self->key];
      (*$self->m)[$self->key] = n;
      return old;
    }
  }
  map_entry(const K& key, std::map<K,V> *owner);
};

// 10.
%typemap(javainterfaces) map_entry<std::string, std::string> "java.util.Map.Entry<String,String>";
// 11.
%typemap(in,numinputs=0) JNIEnv * %{
  $1 = jenv;
%}

// 12.
%extend std::map<std::string, std::string> {
  void all_values(jobjectArray values, JNIEnv *jenv) const {
    assert((jsize)$self->size() == jenv->GetArrayLength(values));
    jsize pos = 0;
    for (std::map<std::string, std::string>::const_iterator it = $self->begin();
         it != $self->end();
         ++it) {
       jenv->SetObjectArrayElement(values, pos++, jenv->NewStringUTF(it->second.c_str()));
    }
  }

  void all_keys(jobjectArray keys, JNIEnv *jenv) const {
    assert((jsize)$self->size() == jenv->GetArrayLength(keys));
    jsize pos = 0;
    for (std::map<std::string, std::string>::const_iterator it = $self->begin();
         it != $self->end();
         ++it) {
       jenv->SetObjectArrayElement(keys, pos++, jenv->NewStringUTF(it->first.c_str()));
    }
  }
}

%template(MapType) std::map<std::string, std::string>;
%template(MapTypeEntry) map_entry<std::string, std::string>;

// 13.
%inline %{
  std::map<std::string, std::string> foo(std::map<std::string, std::string> in) {
    for (std::map<std::string, std::string>::const_iterator it = in.begin();
         it != in.end(); ++it) {
      std::cout << it->first << ": " << it->second << "\n";
    }

    return std::map<std::string, std::string>(in);
  }
%}
  • std_map.i isn't meant to implement any interface/abstract class. We need to rename some of what exposes in order to do so.
  • Since we make our type implement Map (via AbstractMap), it's silly to end up converting from MapType -> MapType when that's literally just a copy operation. The convertMap method now checks for this case as an optimisation.
  • EntrySet is the main requirement of AbstractMap. We have defined (later on) MapTypeEntry to implement the Map.Entry interface for us. This uses some more code inside %extend later on to efficiently get enumerate all the keys as an array. Note that this is not thread-safe, if we change the map whilst this enumeration is in progress weird bad things will happen and possibly not get detected.
  • remove is one of the methods we have to implement in order to be mutable. Both remove and put have to return the old value, so there's a bit of extra Java here to make that happen since C++ maps don't do that.
  • Even size() isn't compatible because of the long/int conversion that's needed. Really we should detect the loss of precision somewhere for very large maps and do something sane for overflows.
  • I got bored of typing java.util.Map everywhere so this makes the generated SWIG code have the import needed.
  • This sets up the MapType to inherit from AbstractMap, so that we proxy and meet the requirements of a Java map rather than doing an extra copy to convert back.
  • The C++ definition of the class that will act as our entry. This just has a key and then a pointer to the map it is owned by. The value isn't stored in the Entry object itself and is always referred back to the underlying map for. This type is immutable too, we can't change the owning map or the key ever.
  • This is what SWIG sees. We supply an extra get/setValue function that calls back to the map it originates from. The pointer to the owning map isn't exposed since we're not required to do so and it's really just an implementation detail.
java.util.Map.Entry<String,String>
  • This is a trick that auto-populates the jenv argument of some code inside %extend that we need to make some JNI calls inside that code.
  • These two methods inside %extend place all of the keys and values respectively into an output array. The array is expected to be the right size when passed in. There's an assert to validate this, but really it should be an exception. Both of these are internal implementation details that probably ought to be private anyway. They get used by all of the functions that require bulk access to keys/values.
foo

Memory management happens for free here since it remains owned by the C++ code. (So you've still got to decide how to manage memory for a C++ container, but that's nothing new). Since the object that gets returned to Java is just a wrapper around a C++ map the elements of the container don't have to outlive it. Here they're also Strings which are special in that they get returned as new objects, if they were smart pointers using SWIG's std::shared_ptr support then everything would work as expected. The only case that would be tricky is maps of pointers to objects. In that case it's the responsibility of the Java programmer to keep the map and its contents alive at least as long as any Java proxies that get returned.

Finally I wrote the following Java to test it:

import java.util.Map;

public class run {
  public static void main(String[] argv) {
    System.loadLibrary("test");

    Map<String,String> m = new MapType();
    m.put("key1", "value1");
    System.out.println(m);
    m = test.foo(m);
    System.out.println(m);
  }
}
swig2.0 -Wall -java -c++ test.i
gcc -Wall -Wextra -shared -o libtest.so -I/usr/lib/jvm/default-java/include -I/usr/lib/jvm/default-java/include/linux test_wrap.cxx
javac run.java
LD_LIBRARY_PATH=. java run
{key1=value1}
key1: value1
{key1=value1}

For completeness could you please post an example code for javaout ? I'm new to SWIG and it's not that obvious. How is memory management handled in the "opposite" code ?

@aberaud sure, I'll try and do it over the weekend. I don't think the OP's approach here is necessarily the right one to take though because it involves lots of copying to and from temporaries. Something like: stackoverflow.com/a/12551108/168175 but for maps instead of vectors is probably better. (Either that or adapt the C++ to work with Java maps instead)

@aberaud - turned out to be a lot more involved than I realised, because the only way to go was the right way and not a quick hack that I initially planned to show.

Passing Java Map to C++ method using SWIG - Stack Over...

java c++ swig
Rectangle 27 13

Using get and set methods within a service you can passing messages between controllers very easily.

var myApp = angular.module("myApp",[]);

myApp.factory('myFactoryService',function(){


    var data="";

    return{
        setData:function(str){
            data = str;
        },

        getData:function(){
            return data;
        }
    }


})


myApp.controller('FirstController',function($scope,myFactoryService){
    myFactoryService.setData("Im am set in first controller");
});



myApp.controller('SecondController',function($scope,myFactoryService){
    $scope.rslt = myFactoryService.getData();
});

in HTML HTML you can check like this

<div ng-controller='FirstController'>  
</div>

<div ng-controller='SecondController'>
    {{rslt}}
</div>

+1 One of those obvious-once-you-are-told-it methods - excellent! I've implemented a more general version with set( key, value) and get(key) methods - a useful alternative to $broadcast.

scope - What's the correct way to communicate between controllers in A...

scope angularjs