Method referring to a pulled in packaged's method moves out of scope when put inside an objects method
The mistake in the code is that @sandbox is an attribute of the class. The value would be initialized when an object of the class is created. Writing the initialization in the class will have no effect. @Maxim has explained this in his answer.
For the second code, when the interpreter runs through the code, it would execute it once. But that code cannot run more than once.
The code should be,
require 'package that has 'accounts''
class Name
def initialize
@sandbox = #working API connection
end
def get_account
@sandbox.accounts do |resp| #This is where error is
resp.each do |account|
if account.name == "John"
name = account.name
end
end
end
end
end
new = Name.new
p new.get_account
How std::packaged_task works
As you can see in the add(...) method body, the instance of
std::packaged_task - task is local variable which scope ends with the
end of the method execution.
yes, it's a local variable of std::shared_ptr<PackedTask>
. when it gets out of scope, it decrements the reference count by 1. if the new reference count is 0, it deletes the object it points to. luckily, jobs
holds a copy of that shared pointer, so that pointed-object stays alive.
The return value ret of std::future type is returned by copy.
Not exactly. it's more possible that ret
is returned by move rather than by copy.
the task goes out of scope and so I expect the connected std::future
instance being returned becomes invalid, is my understanding correct?
Again, task
is a shared pointer. the jobs
queue keeps it alive and probably ret
holds another copy of that shared pointer (to actually pull the result of task
). so nothing becomes invalid as long as the task is in the queue and someone holds the future to that result.
I would expect to store directly the std::packaged_task in order to
hold the reference to the instance being created...?
True, it could have stored std::packaged_task
directly. my guess is that the writer of this library didn't want to mess with uncopiable/unmovable functors. if the result of std::bind
is uncopiable and unmovable, you can't really move the std::packaged_task
into the queue. using a shared pointer solves this problem as you don't copy/move the packaged_task itself, only the pointer. you can however build the the task object directly into the queue, but doing it under a held lock is not such a good practice.
I do agree however, that maybe moving task
into the lambda is way more efficient than copying it.
Java: How to access methods from another class
You need to somehow give class Alpha a reference to cBeta. There are three ways of doing this.
1) Give Alphas a Beta in the constructor. In class Alpha write:
public class Alpha {
private Beta beta;
public Alpha(Beta beta) {
this.beta = beta;
}
and call cAlpha = new Alpha(cBeta) from main()
2) give Alphas a mutator that gives them a beta. In class Alpha write:
public class Alpha {
private Beta beta;
public void setBeta (Beta newBeta) {
this.beta = beta;
}
and call cAlpha = new Alpha(); cAlpha.setBeta(beta); from main(), or
3) have a beta as an argument to doSomethingAlpha. in class Alpha write:
public void DoSomethingAlpha(Beta cBeta) {
cbeta.DoSomethingBeta()
}
Which strategy you use depends on a few things. If you want every single Alpha to have a Beta, use number 1. If you want only some Alphas to have a Beta, but you want them to hold onto their Betas indefinitely, use number 2. If you want Alphas to deal with Betas only while you're calling doSomethingAlpha, use number 3. Variable scope is complicated at first, but it gets easier when you get the hang of it. Let me know if you have any more questions!
Understanding Local Function Capturing of Variables inside Loops
The critical bit of code that you've moved, string output = iFn.ToString();
turns iFn
into a string when it is run
In the first example, it is run after the loop has finished (but "by magic" a single iFn
is still available). Of course, after the loop finishes, iFn is 4 (because that's how the loop stopped). Why is it run after the loop finishes? because you "created a method and stored it in a variable" and the call to turn iFn
into a string is inside this method. You didn't run the method you created while you were in the loop, so iFn was never turned into a string while you were in the loop. The method-in-a-variable was only run afterwards, and because the method contains the code that turns iFn
into a string, it accesses iFn
at whatever current value it has, which is 4.
In the second example iFn is turned into a string as the loop is executing so the value is 0, then 1, then 2, then 3. This is stored in a new variable (called output
) that the method you created in the loop, has access to (again, let's say the method can still access output
, even though it looks like it's out of scope, "by magic"), but the value of output
is generated on each pass of the loop and then given to the method. In essence each of your 4 methods-as-a-variable stored in the list has access to a different variable called output
- the first method' output has a value of 0, the second method's variable called output
has a value of 1..
You could conceive that when you create a method that you will later invoke, the "environment variables" the method had access to at the time it was created, are packaged up with it so that it has its own little environment to execute in. In the first case, each of the 4 methods has access to iFn
at whatever value it is now, whereas in the second they have access to output
at whatever value it had when it was in the loop. Just because the variable is named the same on each pass of the loop doesn't mean it's reusing the same memory location to hold the data
Can Bison verify scope as well as syntax?
Parsers (however produced) typically cannot check scoping rules.
To do scope checking in general, in general you have to build the entire AST and then verify the identifiers are well-scoped. For languages which have static scoping with scopes introduced before variable use, you might be able to do this only the fly in rules. For languages with namespaces, the namespace declaration might occur anywhere, and you can't do it without collecting that namespace and thus the entire program. (The namespace declaration might not even be in the same file as the use; now you have parse an entirely different file).
As a consequence, the usual way scope checking is done is after parsing, over the program tree. Normally if you are going to do anything beyond parsing, you need the tree, and the full symbol table anyway, so this isn't really much of an annoyance.
Some early compilers didn't have the luxury of holding the entire tree in memory. Either they had languages with scope declarations before use, or they were implemented in multiple passes.
Maven 2 assembly with dependencies: jar under scope system not included
I'm not surprised that system scope dependencies are not added (after all, dependencies with a system scope must be explicitly provided by definition). Actually, if you really don't want to put that dependency in your local repository (for example because you want to distribute it as part of your project), this is what I would do:
- I would put the dependency in a "file system repository" local to the project.
I would declare that repository in my
pom.xml
like this:<repositories>
<repository>
<id>my</id>
<url>file://${basedir}/my-repo</url>
</repository>
</repositories>I would just declare the artifact without the
system
scope, this is just a source of troubles:<dependency>
<groupId>sourceforge.jchart2d</groupId>
<artifactId>jchart2d</artifactId>
<version>3.1.0</version>
</dependency>
I'm not 100% sure this will suit your needs but I think it's a better solution than using the system scope.
Update: I should have mentioned that in my original answer and I'm fixing it now. To install a third party library in the file-based repository, use install:install-file
with the localRepositoryPath
parameter:
mvn install:install-file -Dfile=<path-to-file> \
-DgroupId=<myGroup> \
-DartifactId=<myArtifactId> \
-Dversion=<myVersion> \
-Dpackaging=<myPackaging> \
-DlocalRepositoryPath=<path-to-my-repo>
You can paste this as is in a *nix shell. On windows, remove the "\
" and put everything on a single line.
Identifying and solving javax.el.PropertyNotFoundException: Target Unreachable
1. Target Unreachable, identifier 'bean' resolved to null
This boils down to that the managed bean instance itself could not be found by exactly that identifier (managed bean name) in EL like so #{bean}
.
Identifying the cause can be broken down into three steps:
a. Who's managing the bean?
b. What's the (default) managed bean name?
c. Where's the backing bean class?
1a. Who's managing the bean?
First step would be checking which bean management framework is responsible for managing the bean instance. Is it CDI via @Named
? Or is it JSF via @ManagedBean
? Or is it Spring via @Component
? Can you make sure that you're not mixing multiple bean management framework specific annotations on the very same backing bean class? E.g. @Named @ManagedBean
, @Named @Component
, or @ManagedBean @Component
. This is wrong. The bean must be managed by at most one bean management framework and that framework must be properly configured. If you already have no idea which to choose, head to Backing beans (@ManagedBean) or CDI Beans (@Named)? and Spring JSF integration: how to inject a Spring component/service in JSF managed bean?
In case it's CDI who's managing the bean via @Named
, then you need to make sure of the following:
CDI 1.0 (Java EE 6) requires an
/WEB-INF/beans.xml
file in order to enable CDI in WAR. It can be empty or it can have just the following content:<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">
</beans>CDI 1.1 (Java EE 7) without any
beans.xml
, or an emptybeans.xml
file, or with the above CDI 1.0 compatiblebeans.xml
will behave the same as CDI 1.0. When there's a CDI 1.1 compatiblebeans.xml
with an explicitversion="1.1"
, then it will by default only register@Named
beans with an explicit CDI scope annotation such as@RequestScoped
,@ViewScoped
,@SessionScoped
,@ApplicationScoped
, etc. In case you intend to register all beans as CDI managed beans, even those without an explicit CDI scope, use the below CDI 1.1 compatible/WEB-INF/beans.xml
withbean-discovery-mode="all"
set (the default isbean-discovery-mode="annotated"
).<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
version="1.1" bean-discovery-mode="all">
</beans>When using CDI 1.1+ with
bean-discovery-mode="annotated"
(default), make sure that you didn't accidentally import a JSF scope such asjavax.faces.bean.RequestScoped
instead of a CDI scopejavax.enterprise.context.RequestScoped
. Watch out with IDE autocomplete.When using Mojarra 2.3.0-2.3.2 and CDI 1.1+ with
bean-discovery-mode="annotated"
(default), then you need to upgrade Mojarra to 2.3.3 or newer due to a bug. In case you can't upgrade, then you need either to setbean-discovery-mode="all"
inbeans.xml
, or to put the JSF 2.3 specific@FacesConfig
annotation on an arbitrary class in the WAR (generally some sort of an application scoped startup class).When using JSF 2.3 on a Servlet 4.0 container with a
web.xml
declared conform Servlet 4.0, then you need to explicitly put the JSF 2.3 specific@FacesConfig
annotation on an arbitrary class in the WAR (generally some sort of an application scoped startup class). This is not necessary in Servlet 3.x.When using CDI 3.0, the first version with package renamed from
javax.*
tojakarta.*
, then you need to ensure that all deployment descriptor filesbeans.xml
,web.xml
,faces-config.xml
are conform the newjakartaee
schemas and thus not conform the oldjavaee
schemes.<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="https://jakarta.ee/xml/ns/jakartaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee
https://jakarta.ee/xml/ns/jakartaee/beans_3_0.xsd"
version="3.0" bean-discovery-mode="all">
</beans>Non-JEE containers like Tomcat and Jetty doesn't ship with CDI bundled. You need to install it manually. It's a bit more work than just adding the library JAR(s). For Tomcat, make sure that you follow the instructions in this answer: How to install and use CDI on Tomcat?
Your runtime classpath is clean and free of duplicates in CDI API related JARs. Make sure that you're not mixing multiple CDI implementations (Weld, OpenWebBeans, etc). Make sure that you don't provide another CDI or even Java EE API JAR file along webapp when the target container already bundles CDI API out the box.
If you're packaging CDI managed beans for JSF views in a JAR, then make sure that the JAR has at least a valid
/META-INF/beans.xml
(which can be kept empty).
In case it's JSF who's managing the bean via the since 2.3 deprecated @ManagedBean
, and you can't migrate to CDI, then you need to make sure of the following:
The
faces-config.xml
root declaration is compatible with JSF 2.0. So the XSD file and theversion
must at least specify JSF 2.0 or higher and thus not 1.x.<faces-config
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd"
version="2.0">For JSF 2.1, just replace
2_0
and2.0
by2_1
and2.1
respectively.If you're on JSF 2.2 or higher, then make sure you're using
xmlns.jcp.org
namespaces instead ofjava.sun.com
over all place.<faces-config
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_2.xsd"
version="2.2">For JSF 2.3, just replace
2_2
and2.2
by2_3
and2.3
respectively.You didn't accidentally import
javax.annotation.ManagedBean
instead ofjavax.faces.bean.ManagedBean
. Watch out with IDE autocomplete, Eclipse is known to autosuggest the wrong one as first item in the list.You didn't override the
@ManagedBean
by a JSF 1.x style<managed-bean>
entry infaces-config.xml
on the very same backing bean class along with a different managed bean name. This one will have precedence over@ManagedBean
. Registering a managed bean infaces-config.xml
is not necessary since JSF 2.0, just remove it.Your runtime classpath is clean and free of duplicates in JSF API related JARs. Make sure that you're not mixing multiple JSF implementations (Mojarra and MyFaces). Make sure that you don't provide another JSF or even Java EE API JAR file along webapp when the target container already bundles JSF API out the box. See also "Installing JSF" section of our JSF wiki page for JSF installation instructions. In case you intend to upgrade container-bundled JSF from the WAR on instead of in container itself, make sure that you've instructed the target container to use WAR-bundled JSF API/impl.
If you're packaging JSF managed beans in a JAR, then make sure that the JAR has at least a JSF 2.0 compatible
/META-INF/faces-config.xml
. See also How to reference JSF managed beans which are provided in a JAR file?If you're actually using the jurassic JSF 1.x, and you can't upgrade, then you need to register the bean via
<managed-bean>
infaces-config.xml
instead of@ManagedBean
. Don't forget to fix your project build path as such that you don't have JSF 2.x libraries anymore (so that the@ManagedBean
annotation wouldn't confusingly successfully compile).
In case it's Spring who's managing the bean via @Component
, then you need to make sure of the following:
Spring is being installed and integrated as per its documentation. Importantingly, you need to at least have this in
web.xml
:<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>And this in
faces-config.xml
:<application>
<el-resolver>org.springframework.web.jsf.el.SpringBeanFacesELResolver</el-resolver>
</application>(above is all I know with regard to Spring — I don't do Spring — feel free to edit/comment with other probable Spring related causes; e.g. some XML configuration related trouble)
In case it's a repeater component who's managing the (nested) bean via its var
attribute (e.g. <h:dataTable var="item">
, <ui:repeat var="item">
, <p:tabView var="item">
, etc) and you actually got a "Target Unreachable, identifier 'item' resolved to null", then you need to make sure of the following:
The
#{item}
is not referenced inbinding
attribtue of any child component. This is incorrect asbinding
attribute runs during view build time, not during view render time. Moreover, there's physically only one component in the component tree which is simply reused during every iteration round. In other words, you should actually be usingbinding="#{bean.component}"
instead ofbinding="#{item.component}"
. But much better is to get rid of component bining to bean altogether and investigate/ask the proper approach for the problem you thought to solve this way. See also How does the 'binding' attribute work in JSF? When and how should it be used?
1b. What's the (default) managed bean name?
Second step would be checking the registered managed bean name. JSF and Spring use conventions conform JavaBeans specification while CDI has exceptions depending on CDI impl/version.
A
FooBean
backing bean class like below,@Named
public class FooBean {}will in all bean management frameworks have a default managed bean name of
#{fooBean}
, as per JavaBeans specification.A
FOOBean
backing bean class like below,@Named
public class FOOBean {}whose unqualified classname starts with at least two capitals will in JSF and Spring have a default managed bean name of exactly the unqualified class name
#{FOOBean}
, also conform JavaBeans specificiation. In CDI, this is also the case in Weld versions released before June 2015, but not in Weld versions released after June 2015 (2.2.14/2.3.0.B1/3.0.0.A9) nor in OpenWebBeans due to an oversight in CDI spec. In those Weld versions and in all OWB versions it is only with the first character lowercased#{fOOBean}
.If you have explicitly specified a managed bean name
foo
like below,@Named("foo")
public class FooBean {}or equivalently with
@ManagedBean(name="foo")
or@Component("foo")
, then it will only be available by#{foo}
and thus not by#{fooBean}
.
1c. Where's the backing bean class?
Third step would be doublechecking if the backing bean class is at the right place in the built and deployed WAR file. Make sure that you've properly performed a full clean, rebuild, redeploy and restart of the project and server in case you was actually busy writing code and impatiently pressing F5 in the browser. If still in vain, let the build system produce a WAR file, which you then extract and inspect with a ZIP tool. The compiled .class
file of the backing bean class must reside in its package structure in /WEB-INF/classes
. Or, when it's packaged as part of a JAR module, the JAR containing the compiled .class
file must reside in /WEB-INF/lib
and thus not e.g. EAR's /lib
or elsewhere.
If you're using Eclipse, make sure that the backing bean class is in src
and thus not WebContent
, and make sure that Project > Build Automatically is enabled. If you're using Maven, make sure that the backing bean class is in src/main/java
and thus not in src/main/resources
or src/main/webapp
.
If you're packaging the web application as part of an EAR with EJB+WAR(s), then you need to make sure that the backing bean classes are in WAR module and thus not in EAR module nor EJB module. The business tier (EJB) must be free of any web tier (WAR) related artifacts, so that the business tier is reusable across multiple different web tiers (JSF, JAX-RS, JSP/Servlet, etc).
2. Target Unreachable, 'entity' returned null
This boils down to that the nested property entity
as in #{bean.entity.property}
returned null
. This usually only exposes when JSF needs to set the value for property
via an input component like below, while the #{bean.entity}
actually returned null
.
<h:inputText value="#{bean.entity.property}" />
You need to make sure that you have prepared the model entity beforehand in a @PostConstruct
, or <f:viewAction>
method, or perhaps an add()
action method in case you're working with CRUD lists and/or dialogs on same view.
@Named
@ViewScoped
public class Bean {
private Entity entity; // +getter (setter is not necessary).
@Inject
private EntityService entityService;
@PostConstruct
public void init() {
// In case you're updating an existing entity.
entity = entityService.getById(entityId);
// Or in case you want to create a new entity.
entity = new Entity();
}
// ...
}
As to the importance of @PostConstruct
; doing this in a regular constructor would fail in case you're using a bean management framework which uses proxies, such as CDI. Always use @PostConstruct
to hook on managed bean instance initialization (and use @PreDestroy
to hook on managed bean instance destruction). Additionally, in a constructor you wouldn't have access to any injected dependencies yet, see also NullPointerException while trying to access @Inject bean in constructor.
In case the entityId
is supplied via <f:viewParam>
, you'd need to use <f:viewAction>
instead of @PostConstruct
. See also When to use f:viewAction / preRenderView versus PostConstruct?
You also need to make sure that you preserve the non-null
model during postbacks in case you're creating it only in an add()
action method. Easiest would be to put the bean in the view scope. See also How to choose the right bean scope?
3. Target Unreachable, 'null' returned null
This has actually the same cause as #2, only the (older) EL implementation being used is somewhat buggy in preserving the property name to display in the exception message, which ultimately incorrectly exposed as 'null'. This only makes debugging and fixing a bit harder when you've quite some nested properties like so #{bean.entity.subentity.subsubentity.property}
.
The solution is still the same: make sure that the nested entity in question is not null
, in all levels.
4. Target Unreachable, ''0'' returned null
This has also the same cause as #2, only the (older) EL implementation being used is buggy in formulating the exception message. This exposes only when you use the brace notation []
in EL as in #{bean.collection[index]}
where the #{bean.collection}
itself is non-null, but the item at the specified index doesn't exist. Such a message must then be interpreted as:
Target Unreachable, 'collection[0]' returned null
The solution is also the same as #2: make sure that the collection item is available.
5. Target Unreachable, 'BracketSuffix' returned null
This has actually the same cause as #4, only the (older) EL implementation being used is somewhat buggy in preserving the iteration index to display in the exception message, which ultimately incorrectly exposed as 'BracketSuffix' which is really the character ]
. This only makes debugging and fixing a bit harder when you've multiple items in the collection.
Other possible causes of javax.el.PropertyNotFoundException
:
- javax.el.ELException: Error reading 'foo' on type com.example.Bean
- javax.el.ELException: Could not find property actionMethod in class com.example.Bean
- javax.el.PropertyNotFoundException: Property 'foo' not found on type com.example.Bean
- javax.el.PropertyNotFoundException: Property 'foo' not readable on type java.lang.Boolean
- javax.el.PropertyNotFoundException: Property not found on type org.hibernate.collection.internal.PersistentSet
- Outcommented Facelets code still invokes EL expressions like #{bean.action()} and causes javax.el.PropertyNotFoundException on #{bean.action}
Exclude all transitive dependencies of a single dependency
For maven2 there isn't a way to do what you describe. For maven 3, there is. If you are using maven 3 please see another answer for this question
For maven 2 I'd recommend creating your own custom pom for the dependency that has your <exclusions>. For projects that need to use that dependency, set the dependency to your custom pom instead of the typical artifact. While that does not necessarily allow you exclude all transitive dependencies with a single <exclusion>, it does allow you only have to write your dependency once and all of your projects don't need to maintain unnecessary and long exclusion lists.
Related Topics
Hook Before All Delyed Job Success Callback to Save Successfully Completed Jobs
How to Display Error Messages in a Multi-Model Form with Transaction
Certificate to Pem to Certificate Not Working: Nested Asn1 Error
Bind and Destructure Block Arguments
Understanding Ruby Method Parameters Syntax
Why Does 'Defined' Return a String or Nil
New to Ruby and Am Having Trouble with Load_Path
Pageobject with Ruby - Set Text in a Text Field Only Works in the Main File
How to Sort a Ruby Array by Two Conditions
Ruby Instance Method & Conditional Local Variable Assignment with Same Name
My Classes Can't Use Shoes Methods Like Para
Replicating Xml Request with Savon/Ruby
Ruby Autoload Conflicts Between Gmail and Parse_Resource Gems
How to Know If an Io Is Empty Without Reading It
Render Erb from Database into View Problem Please Help!
When Passing a Ruby Array as an Argument, Why Does '<<' Append While '+=' Does Not