w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML Categories
How to specify file path in Java Bean in a web application?
First of all, these kind of internal files should reside in an inaccessible spot, in WebContent/WEB-INF. You could get a file system File: File file = request.getServletContext().getRealPath("/resources/db/models.txt"); If you store the file as real resource (in the class path), you can use: InputStream in = getClass().getResourceAsStream("/db/models.txt"); Please specify the character encoding: sc = new Scanner(new File(filePath), "UTF-8"); So the same encoding is used whether developing under Windows or deploying on a Linux server. Because the default encoding is platform dependent. ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();

Categories : Java

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'helper' . No unique bean of type [java.lang.String]
Try Droping the @Autowired annotation in Ctor and configuring it in xml: <bean id="helper" class="test.Helper"> <constructor-arg ref="clientFactory" /> <constructor-arg ref="modelManager" /> <constructor-arg type="java.lang.String" value="http://test.com" /> <constructor-arg ref="securityService" /> </bean>

Categories : Java

Stack trace prints everything on one line in log file (Java)
You could use Java's Logger. With Logger, this should do the trick: Logger = logger = Logger.getLogger(<YourClass>); logger.log(Level.SEVERE, <your message>, e); If you want to do it the hard way you should keep in mind that getStackTrace() returns an array, so you'll have to process it.

Categories : Java

Unable to connect to MySQL Amazon RDS from Java app on Elastic Beanstalk, java.sql.SQLException: No suitable driver
The issue was that Elastic Beanstalk was adding quotes around the JDBC_CONNECTION_STRING environment variable that I was passing in. The issue and solution is described in this thread: https://forums.aws.amazon.com/thread.jspa?threadID=115043 (Adding the following to my .ebextensions config fixed the issue): commands: patch_tomcat: command: sed -i.bak s#"/usr/sbin/tomcat7"#"/usr/sbin/tomcat7-elasticbeanstalk"#g /etc/init.d/tomcat7

Categories : Java

Elastic Beanstalk's Elastic Load Balancer name
Unfortunately the answer is no to the first 2. The last one, you are able to do it, but it more or less goes against the flow of Elastic beanstalk. You would need to create your own ELB with whatever name you like and then put it in front ot the instance that is created by beanstalk. You would need need to delete the ELB that beanstalk created so that it's not sitting there costing you money. I can't remember if beanstalk boots its environments via an AutoScaling group, but if it does, you'll need to associate that AutoScaling group with your new ELB. After creating and syncing all of that up, you need to point your CNAME to your new custom made ELB. That should work.

Categories : Amazon

Invalid property 'username' of bean class [java.util.ArrayList]: Bean property 'username' is not readable or has an invalid getter method
Try to this code: @RequestMapping(value="/userList") public ModelAndView getUserList(){ List<User> userList = userService.getUserList(); ModelAndView mav = new ModelAndView("userList"); mav.addObject("userList", userList); mav.addObject("user", user); return mav; }

Categories : Spring

elastic map reduce "keep alive" specification in the java api
You need to set withActionOnFailure to let the API know what to do when a step fails, and this has to be set on per step basis. You must be having withActionOnFailure("TERMINATE_JOB_FLOW") for your StepConfigs. Change them to withActionOnFailure("CANCEL_AND_WAIT"). Following is the full code to launch a cluster using Java API taken from here, just replacing the needful: AWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey); AmazonElasticMapReduceClient emr = new AmazonElasticMapReduceClient(credentials); StepFactory stepFactory = new StepFactory(); StepConfig enabledebugging = new StepConfig() .withName("Enable debugging") .withActionOnFailure("CANCEL_AND_WAIT") //here is the change .withHadoopJarStep(stepFactory.newEnabledebuggingSt

Categories : Misc

Bulk update via elastic search Java API throws exception
As the exception says, no requests were added to the BulkRequest object. Debug if the records you add in the for loop are actually being added to the builder object. Found this post recently with the same issue: ActionRequestValidationException

Categories : Java

What method(s) do I use to configure/update an Elastic Load Balancer via Java?
My bad. Forgot to execute the requests against the ELB variable. The code below creates the health check and assigns the instances associated with the ELB. Hope this helps the next person asking this question. ConfigureHealthCheckResult healthResult = myELB.configureHealthCheck(healthCheckReq); RegisterInstancesWithLoadBalancerResult registerResult = myELB.registerInstancesWithLoadBalancer(regInst);

Categories : Java

Java performance testing changes when executing code from callback class. Java stack frame issue?
These results aren't really "dramatic." The averages for the 1000000 runs are: staticMethod1 explicit: 14541456.7 (14.5 ns per iteration) callback: 15272563.3 (15.2 ns per iteration) slowdown: 0.7 ns per iteration staticMethod2 explicit: 2167413.1 (2.2 ns per iteration) callback: 9494495.2 (9.5 ns per iteration) slowdown: (7 ns per iteration) The fact that the slowdown between these is off by (almost exactly) an order of magnitude is weird, but the big thing is that the callback approach slowed down by at most about 7 ns. That's not a whole lot. UPDATE More results you have posted, with the order of testing method2 then method1, are consistent with the following: the JVM initially runs your code in interpreted mode, profiling it; it sees that you always call the same implmenta

Categories : Java

Exception in thread "main" java.lang.NoClassDefFoundError in AWS Elastic Map Reduce
The 3rd party dependency isn't included in the job jar by default and hence the error message you are seeing. It works in Eclipse standalone mode as Eclipse knows to add the jar to the classpath at execution time. You have two choices: Unpack this jar and repack your classes and the 3rd party dependency jars into a single 'uber' or monolithic jar - maven has a jar-with-dependencies assembly for doing this (if you're using maven, which i'd personally recommend) Use the -libjars argument combined with the ToolRunner method for submitting jobs - this will ensure your 3rd party jars are submitted with your job hadoop jar myJar.jar -libjars ejml.jar MainClass.class

Categories : Java

Elastic Beanstalk .ebextensions .config file run's occasionally, not others
This is confirmed. If using a ruby hash with keys that have been symbolized, you need to unsymbolize the keys before to_yaml or else post process and remove the leading ':' semi-colon. Also confirmed, if eb doesn't like your .config file on deploy, it just swallows it and doesn't even log anything!

Categories : Ruby On Rails

Writing file to bucket fails on Elastic Beanstalk application
I was getting same error during zip file upload on S3 and finally this worked for me: zip_data = File.read(zip_file_path) means, zip_data will be the object at the zip file path that is located in your tmp directory. Hope, this will work for you also.

Categories : Ruby

Java XML Bean and XML xml parser
Xml beans is a way to serialize your data. Take a look to the ecore technology: there is a way to create xmi for any bean object your created. There is a really good article on Vogella about it: http://www.vogella.com/articles/EclipseEMFPersistence/article.html

Categories : Java

Java Bean will create more than once
In Stateful Session Bean, the instance variables represent the state of a unique client-bean session. So, each client will have its own instance. If you want instance of the Bean, you can use Statefull Session bean or Singleton Session bean. U can see: http://docs.oracle.com/javaee/5/tutorial/doc/bnbly.html

Categories : Java

How to map Java Bean property to another name for output?
What if you write a method, that expects a field name (property name) and returns a nicely formatted output? For example: public String formatProperty(String propertyName, String userFriendlyLabel) { Field someField = this.getClass().getField(propertyName); Object value = null; if(someField != null) { value = someField.get(this); } return userFriendlyLabel + ": " + value; }

Categories : Java

How to @Inject A Bean into a Java Class?
If you use spring version 3.1 and higher - add annotation @ComponentScan({"by.company.app"}) after @Configuration annotation After that you must tell spring that your DatabaseQuery must be managed by spring. So add @Component before class declaration: @Component public class DatabaseQuery { // code } After that spring will manage both dataSource and query object and inject dataSource to query.

Categories : Java

Instance variable in Java Spring Bean
I guess in your case if you define the scope of your bean which has your instance variables as Singleton that should do. As per Spring reference document, below is the definition for Singleton scoped bean. To put it another way, when you define a bean definition and it is scoped as a singleton, the Spring IoC container creates exactly one instance of the object defined by that bean definition. This single instance is stored in a cache of such singleton beans, and all subsequent requests and references for that named bean return the cached object. Singleton is the Default scope that your bean will be put into if you don't specify. Also, below statement should be kept in mind, if you try to handle your case using Spring's bean scope approach. This approach is powerful and flexible i

Categories : Java

Custom class variables in a Java Bean
Yes, you can. You can implement your own business logic using POJO defined by yourself plugging reusable components as well. If you use JSF remember to create setter and getter for your variables if you want to access them from your JSP/Facelets pages. The naming convention is pretty standard, if you have a String named 'foo' the framework will call the public String getFoo() { return foo; } method.

Categories : Java

How to get externally defined bean in java config
Either add a field in your configuration class and annotate it with @Autowired or add @Autowired to the method and pass in an argument of the type. public class MyConfig { @Autowired private Foo foo; @Bean public Bar bar() { Bar bar = new Bar(); bar.setFoo(foo); // foo is defined in somebeans.xml return bar; } } or public class MyConfig { @Bean @Autowired public Bar bar(Foo foo) { Bar bar = new Bar(); bar.setFoo(foo); // foo is defined in somebeans.xml return bar; } } This is all explained in the reference guide.

Categories : Java

Access properties of 1 java bean in session using c:out tag
Why are you mixing JSTL and scriplets? You can't access the variables set in scriplets, inside an EL. Better option is to avoid that scriplet alltogether, and just use EL, to access attributes from session. You can directly use the EL expression: <textarea>${etBeanInServlet.ticketDesc}</textarea> you can also explicitly specify that you are fetching the attribute from session scope (only when there is conflict between variables set in various scopes) like so: <textarea>${sessionScope.etBeanInServlet.ticketDesc}</textarea> and finally using using JSTL <c:out> tag, which will escape XML for you: <textarea><c:out value="${etBeanInServlet.ticketDesc}" /></textarea>

Categories : Java

convert with JAXB (xjc) at a java bean class
Problem is with xmlns:xlink="http://www.w3.org/1999/xlink" Solution: Create and use binding.xjb: <jxb:bindings version="2.0" xmlns:jxb="http://java.sun.com/xml/ns/jaxb" xmlns:xs="http://www.w3.org/2001/XMLSchema" > <jxb:bindings schemaLocation="http://www.w3.org/1999/xlink.xsd" node="/xs:schema"> <jxb:bindings node="//xs:attributeGroup[@name='locatorAttrs']"> <jxb:bindings node=".//xs:attribute[@ref='xlink:title']"> <jxb:property name="title1"/> </jxb:bindings> </jxb:bindings> <jxb:bindings node="//xs:attributeGroup[@name='arcAttrs']"> <jxb:bindings node=".//xs:attribute[@ref='xlink:title']"> <jxb:property na

Categories : Java

Java Beans instantiating wrong bean
Based on comments, I can only assume that the Generator class looks something like this public class Generator { private static length; private static categories; //getters/setters } Given that i dont have a full class to work with, i can only recommend removing the static modifier as it would contradict the way you want to use the class.

Categories : Java

how to use managed Bean in another project in the same Java EE application
Just create a Jar which goes into your final Java EE application (referenced by both of the projects if you're using Maven). Then, add the simplest faces configuration file in your Jar's META-INF directory: <?xml version="1.0" encoding="UTF-8"?> <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"> </faces-config> That will make JSF scan this Jar's content. After that, just use annotations in the classes you want them to be managed beans: @ManagedBean @SessionScoped public class SessionScopedBean{ .... } That's all, for more info you can visit this link.

Categories : Java

Java Bean getter not returning values
This is wrong way to access the bean properties using EL: This system's java version is #{properties.getJavaVersion} It should be This system's java version is #{properties.javaVersion} Since getJavaVersion() is the getter , hence EL will look for javaVersion property. Same applies to other fields. If you have a bean class : public class Foo { int bar; public int getBar(){ return bar; } } The bar property should be accessed as #{bean.bar}.

Categories : Java

Error creating bean with name 'flowBuilderServices': Initialization of bean failed with spring web flow
You need a reference to a view resolver. like so: <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/" /> <property name="suffix" value=".jsp" /> </bean>

Categories : Maven

Spring Testing - Inject mocked bean with nested bean dependencies
You could use standalone mockMvc if you do want to unit test the controller. private MockMvc mockMvc; private SomeController controller = new SomeController(); @Mock private ResourceAdminService resourceAdminService; @Before public void setup() throws Exception { controller.setResourceAdminService(resourceAdminService); this.mockMvc = MockMvcBuilders.standaloneSetup(controller).build(); } If you still want to setup an ApplicationContext, but it's too annoying with the DI. Maybe you'll interested in this article(http://java.dzone.com/articles/how-use-mockstub-spring). But the Strategy C:Dynamic Injecting will rebuild an ApplicationContext per test which could slow you tests if you have too many @Test methods.

Categories : Java

Concurrency control with method invocation in EJB bean vs. Spring bean
EJB declarative concurency management applies only to singleton session beans, see javax.ejb.ConcurrencyManagement API. Regular session beans have no thread safety issues because containter insures that only one thread accesses a bean instance at any given time. As for Spring beans concurrency is not managed by container, programmers themselves should take care of it.

Categories : Java

When to declare a spring bean as private static when the bean is singleton?
If by declaring the bean as static, you mean something like @Bean public static MyBean myBean() { return new MyBean(); } then the benefit of this is to have your bean generated before the instance method beans. You would use this for example with a BeanFactoryPostProcessor which states: Application contexts can auto-detect BeanFactoryPostProcessor beans in their bean definitions and apply them before any other beans get created. The Spring Java configuration way for these to be auto-detected and initialized before the rest of your beans is to declare and initialize them with static methods. For example, @Bean public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { return new PropertySourcesPlaceholderConfigurer(); } Spring will de

Categories : Spring

Why does rich:inputNumberSlider does not update backing bean (@Managed Bean)
The setSecurityLevel setter will never be invoked till you submit the form where your rich:inputNumberSlider is contained. Alternatively, you can set the value whenever the inputNumberSlider is changed, adding an ajax per event processing, which will execute your component (I don't use richfaces, but that would be the desired format): <h:form> <rich:inputNumberSlider id="severityLevel" value="#{pubController.severityLevel}" minValue="1" maxValue="3" maxlength="1" > <a4j:ajax event="change" execute="@this" /> </rich:inputNumberSlider> </h:form> Generally, that kind of behaviour is unrequired unless you want to perform some kind of validation while user is changing the input value (it also could be useful to render dependent componen

Categories : JSF

Dynamically adding a list of bean references to bean definition
Take a look at org.springframework.beans.factory.support.ManagedList That's what <util:list/> uses to compile a list. Create a ManagedList as your variable "checks" and set that object as the property value.

Categories : Spring

How can I access Spring bean from Message-driven bean in JBoss AS 7
A static holder for the context is not really a good idea. To make your beans available to other applications in a Java EE environment, you should consider making use of JNDI. Unfortunately, there is no plain JNDI exporter available out of the box, but it's fairly easy to write one yourself, as shown in this blog post: http://maestro-lab.blogspot.ro/2009/01/how-to-export-spring-managed-bean-to.html There is however a JndiRmiServiceExporter that you may want to look at. Once your beans are bound to names in JNDI, they can be referenced using standard CDI in your message bean without worrying about class loading issues.

Categories : Spring

Spring: Return JSON response From A Java Bean
We use fastjson to JSONize java beans. It's fast and convenient. public @ResponseBody String showLesson() { Map<String, Object> map = new HashMap<String, Object>(); return JSON.toJSONString(map); }

Categories : Java

XML being returned in String form needs to be Converted into a java bean
You should use JAXB for this task, it's a Java standard for converting XML files into objects. StringReader reader = new StringReader(xmlString); JAXBContext jaxbContext = JAXBContext.newInstance(Cities.class); Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); Cities response = (Cities) unmarshaller.unmarshal(reader); You also need to annotate your Cities class like this @XmlRootElement public class Cities { @XmlElement private String coutry; @XmlElement private String city; //setters and getters } This should work for you. You can also use @XmlElement(name="") to customize binding of XML elements to Java properties.

Categories : Java

Java spring persistence error creating bean
Turns out there was a problem with the code, some changes within the classes that were not propagated through the rest of the code that was using the implicit DB tables. After forking before the commit in question, the error was gone completely. broken code here this helped Seems this is somehow also connected to a bug in the hibernate implementation, got rid of it with some annotations

Categories : Java

How to upload and save an attachment via XPages Java Bean
I have code that processes an uploaded file in Java. The file is uploaded with the normal fileUpload control and then I call the following Java code from a button (that does a full refresh - so that the document including the uploaded file is saved). In the Java code you can do whatever checks you want (filename, filesize etc.): public void importFile() { facesContext = FacesContext.getCurrentInstance(); ExternalContext externalContext = facesContext.getExternalContext(); // get a handle an the uploaded file HttpServletRequest request = (HttpServletRequest) externalContext.getRequest(); String fileUploadID = JSFUtil.findComponent("uploadFile").getClientId(FacesContext.getCurrentInstance()); UploadedFile uploadedFile = ((UploadedFile) request.getParameterMap().get

Categories : Java

Java bean validation - override default message
You need to use the ConstraintValidatorContext to select the right message template. You can see an example in the Hibernate Validator docs - http://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single/#validator-customconstraints-validator. Effectively you do something like: constraintContext.disableDefaultConstraintViolation(); constraintContext.buildConstraintViolationWithTemplate( "{package.ValidFoo.message_constraint1}" ) .addConstraintViolation();

Categories : Java

Java jsr 303 accessing bean fields from annotated field
Well, I guess it's not possible, so I stick with class anotated solution: Cross field validation with Hibernate Validator (JSR 303)

Categories : Java

java.lang.NoSuchMethodException: Bean has no property named
Just a guess, but does it make a difference if you rename the instance variable YESBarePO.CostCenter to be YESBarePO.costCenter instead? Unlike .NET, for instance, the standard Java idiom is to use lowerCamelCase for instance variables and my experience suggests that some bean mappers require this convention to be honoured in order to work.

Categories : Java

How to avoid 400 error in spring mvc when binding as java Bean
I have solved this problem. Because I'm a new to Spring MVC. I tried several methods. But I think follow methods may help if you meet the same problems. add in your controller @InitBinder protected void initBinder( WebDataBinder binder) throws ServletException { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); dateFormat.setLenient(false); binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false)); } But I meet the new questions. If I submit form in value "". I always get error.code typeMismatch. I already configed in message.properties file #bean level error message typeMismatch.order.dueDate = order.dueDate format not match "YYYY-MM-DD" #global type not match message typeMismatch = data type not match Bu

Categories : Spring



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.