java,spring,hibernate,spring-mvc,tomcat , How to get some utf-8 characters using hibernate and spring mvc in database?


How to get some utf-8 characters using hibernate and spring mvc in database?

Question:

Tag: java,spring,hibernate,spring-mvc,tomcat

I have developed small server program. When I extract tuple from database, some characters become ÇѱÛÃàÁ¦. I modify server.xml. However ÇѱÛÃàÁ¦ characters still appear. Help me. How can I get correct characters?

This is my server.xml. (I use apache tomcat 7.0 server.)

<?xml version="1.0" encoding="UTF-8"?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
--><!-- Note:  A "Server" is not itself a "Container", so you may not
     define subcomponents such as "Valves" at this level.
     Documentation at /docs/config/server.html
 --><Server port="8005" shutdown="SHUTDOWN">
  <Listener className="org.apache.catalina.startup.VersionLoggerListener"/>
  <!-- Security listener. Documentation at /docs/config/listeners.html
  <Listener className="org.apache.catalina.security.SecurityListener" />
  -->
  <!--APR library loader. Documentation at /docs/apr.html -->
  <Listener SSLEngine="on" className="org.apache.catalina.core.AprLifecycleListener"/>
  <!--Initialize Jasper prior to webapps are loaded. Documentation at /docs/jasper-howto.html -->
  <Listener className="org.apache.catalina.core.JasperListener"/>
  <!-- Prevent memory leaks due to use of particular java/javax APIs-->
  <Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener"/>
  <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener"/>
  <Listener className="org.apache.catalina.core.ThreadLocalLeakPreventionListener"/>

  <!-- Global JNDI resources
       Documentation at /docs/jndi-resources-howto.html
  -->
  <GlobalNamingResources>
    <!-- Editable user database that can also be used by
         UserDatabaseRealm to authenticate users
    -->
    <Resource auth="Container" description="User database that can be updated and saved" factory="org.apache.catalina.users.MemoryUserDatabaseFactory" name="UserDatabase" pathname="conf/tomcat-users.xml" type="org.apache.catalina.UserDatabase"/>
  </GlobalNamingResources>

  <!-- A "Service" is a collection of one or more "Connectors" that share
       a single "Container" Note:  A "Service" is not itself a "Container",
       so you may not define subcomponents such as "Valves" at this level.
       Documentation at /docs/config/service.html
   -->
  <Service name="Catalina">

    <!--The connectors can use a shared executor, you can define one or more named thread pools-->
    <!--
    <Executor name="tomcatThreadPool" namePrefix="catalina-exec-"
        maxThreads="150" minSpareThreads="4"/>
    -->


    <!-- A "Connector" represents an endpoint by which requests are received
         and responses are returned. Documentation at :
         Java HTTP Connector: /docs/config/http.html (blocking & non-blocking)
         Java AJP  Connector: /docs/config/ajp.html
         APR (HTTP/AJP) Connector: /docs/apr.html
         Define a non-SSL HTTP/1.1 Connector on port 8080
    -->
    <Connector URIEncoding="UTF-8" connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443"/>
    <!-- A "Connector" using the shared thread pool-->
    <!--
    <Connector executor="tomcatThreadPool"
               port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" />
    -->
    <!-- Define a SSL HTTP/1.1 Connector on port 8443
         This connector uses the BIO implementation that requires the JSSE
         style configuration. When using the APR/native implementation, the
         OpenSSL style configuration is required as described in the APR/native
         documentation -->
    <!--
    <Connector port="8443" protocol="org.apache.coyote.http11.Http11Protocol"
               maxThreads="150" SSLEnabled="true" scheme="https" secure="true"
               clientAuth="false" sslProtocol="TLS" />
    -->

    <!-- Define an AJP 1.3 Connector on port 8009 -->
    <Connector URIEncoding="UTF-8" port="8009" protocol="AJP/1.3" redirectPort="8443"/>


    <!-- An Engine represents the entry point (within Catalina) that processes
         every request.  The Engine implementation for Tomcat stand alone
         analyzes the HTTP headers included with the request, and passes them
         on to the appropriate Host (virtual host).
         Documentation at /docs/config/engine.html -->

    <!-- You should set jvmRoute to support load-balancing via AJP ie :
    <Engine name="Catalina" defaultHost="localhost" jvmRoute="jvm1">
    -->
    <Engine defaultHost="localhost" name="Catalina">

      <!--For clustering, please take a look at documentation at:
          /docs/cluster-howto.html  (simple how to)
          /docs/config/cluster.html (reference documentation) -->
      <!--
      <Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"/>
      -->

      <!-- Use the LockOutRealm to prevent attempts to guess user passwords
           via a brute-force attack -->
      <Realm className="org.apache.catalina.realm.LockOutRealm">
        <!-- This Realm uses the UserDatabase configured in the global JNDI
             resources under the key "UserDatabase".  Any edits
             that are performed against this UserDatabase are immediately
             available for use by the Realm.  -->
        <Realm className="org.apache.catalina.realm.UserDatabaseRealm" resourceName="UserDatabase"/>
      </Realm>

      <Host appBase="webapps" autoDeploy="true" name="localhost" unpackWARs="true">

        <!-- SingleSignOn valve, share authentication between web applications
             Documentation at: /docs/config/valve.html -->
        <!--
        <Valve className="org.apache.catalina.authenticator.SingleSignOn" />
        -->

        <!-- Access log processes all example.
             Documentation at: /docs/config/valve.html
             Note: The pattern used is equivalent to using pattern="common" -->
        <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs" pattern="%h %l %u %t &quot;%r&quot; %s %b" prefix="localhost_access_log." suffix=".txt"/>

      <Context docBase="server" path="/jinggumdari" reloadable="true" source="org.eclipse.jst.jee.server:server"/></Host>
    </Engine>
  </Service>
</Server>

This is my web.xml.

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 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-app_2_5.xsd">

	<!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>/WEB-INF/spring/root-context.xml</param-value>
	</context-param>
	
	<!-- Creates the Spring Container shared by all Servlets and Filters -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

	<!-- Processes application requests -->
	<servlet>
		<servlet-name>appServlet</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
		
	<servlet-mapping>
		<servlet-name>appServlet</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
	
	<filter>
		<filter-name>encodingFilter</filter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>UTF-8</param-value>
		</init-param>
		<init-param>
			<param-name>forceEncoding</param-name>
			<param-value>true</param-value>
		</init-param>
	</filter>

	<filter-mapping>
		<filter-name>encodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

</web-app>

This is my servlet-context.xml.

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd">
	<!-- DispatcherServlet Context: defines this servlet's request-processing 
		infrastructure -->

	<!-- Enables the Spring MVC @Controller programming model -->
	<annotation-driven />

	<!-- Handles HTTP GET requests for /resources/** by efficiently serving 
		up static resources in the ${webappRoot}/resources directory -->
	<resources mapping="/resources/**" location="/resources/" />

	<!-- Resolves views selected for rendering by @Controllers to .jsp resources 
		in the /WEB-INF/views directory -->
	<beans:bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<beans:property name="prefix" value="/WEB-INF/views/" />
		<beans:property name="suffix" value=".jsp" />
	</beans:bean>

	<beans:bean
		class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
		<beans:property name="favorPathExtension" value="true" />
		<beans:property name="ignoreAcceptHeader" value="true" />

		<beans:property name="mediaTypes">
			<beans:map>
				<beans:entry key="json" value="application/json" />
				<beans:entry key="html" value="text/html" />
			</beans:map>
		</beans:property>
	</beans:bean>

	<context:component-scan base-package="kr.ac.jbnu.jinggumdari" />

	<beans:bean
		class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />

	<beans:bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
		destroy-method="close">
		<beans:property name="driverClassName" value="com.mysql.jdbc.Driver" />
		<beans:property name="url"
			value="jdbc:mysql://localhost:3306/jinggumdari" />
		<beans:property name="username" value="root" />
		<beans:property name="password" value="mysql1234" />
	</beans:bean>

	<!-- Hibernate 4 SessionFactory Bean definition -->
	<beans:bean id="hibernate4AnnotatedSessionFactory"
		class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
		<beans:property name="dataSource" ref="dataSource" />
		<beans:property name="annotatedClasses">
			<beans:list>
				<beans:value>kr.ac.jbnu.jinggumdari.model.Member</beans:value>
				<beans:value>kr.ac.jbnu.jinggumdari.model.Festival</beans:value>
				<beans:value>kr.ac.jbnu.jinggumdari.model.FestivalImage</beans:value>
				<beans:value>kr.ac.jbnu.jinggumdari.model.Interest</beans:value>
				<beans:value>kr.ac.jbnu.jinggumdari.model.Review</beans:value>
				<beans:value>kr.ac.jbnu.jinggumdari.model.ReviewImage</beans:value>
				<beans:value>kr.ac.jbnu.jinggumdari.model.Search</beans:value>
				<beans:value>kr.ac.jbnu.jinggumdari.model.RouteInfo</beans:value>
				<beans:value>kr.ac.jbnu.jinggumdari.model.Route</beans:value>
				<beans:value>kr.ac.jbnu.jinggumdari.model.Writing</beans:value>
			</beans:list>
		</beans:property>
		<beans:property name="hibernateProperties">
			<beans:props>
				<beans:prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect
				</beans:prop>
				<beans:prop key="hibernate.show_sql">true</beans:prop>
			</beans:props>
		</beans:property>
		<beans:property name="packagesToScan" value="com.hibernate.yourpackage" />
	</beans:bean>

	<beans:bean id="memberDAO" class="kr.ac.jbnu.jinggumdari.DAO.MemberDAOImpl">
		<beans:property name="sessionFactory"
			ref="hibernate4AnnotatedSessionFactory" />
	</beans:bean>
	<beans:bean id="memberService"
		class="kr.ac.jbnu.jinggumdari.serviceImplementation.MemberServiceImpl">
		<beans:property name="memberDAO" ref="memberDAO"></beans:property>
	</beans:bean>
	
	<beans:bean id="festivalDAO" class="kr.ac.jbnu.jinggumdari.DAO.FestivalDAOImpl">
		<beans:property name="sessionFactory"
			ref="hibernate4AnnotatedSessionFactory" />
	</beans:bean>
	<beans:bean id="festivalService"
		class="kr.ac.jbnu.jinggumdari.serviceImplementation.FestivalServiceImpl">
		<beans:property name="festivalDAO" ref="festivalDAO"></beans:property>
	</beans:bean>
	
	<beans:bean id="festivalImageDAO" class="kr.ac.jbnu.jinggumdari.DAO.FestivalImageDAOImpl">
		<beans:property name="sessionFactory"
			ref="hibernate4AnnotatedSessionFactory" />
	</beans:bean>
	<beans:bean id="festivalImageService"
		class="kr.ac.jbnu.jinggumdari.serviceImplementation.FestivalImageServiceImpl">
		<beans:property name="festivalImageDAO" ref="festivalImageDAO"></beans:property>
	</beans:bean>
	
	<beans:bean id="interestDAO" class="kr.ac.jbnu.jinggumdari.DAO.InterestDAOImpl">
		<beans:property name="sessionFactory"
			ref="hibernate4AnnotatedSessionFactory" />
	</beans:bean>
	<beans:bean id="interestService"
		class="kr.ac.jbnu.jinggumdari.serviceImplementation.InterestServiceImpl">
		<beans:property name="interestDAO" ref="interestDAO"></beans:property>
	</beans:bean>

	<beans:bean id="reviewDAO" class="kr.ac.jbnu.jinggumdari.DAO.ReviewDAOImpl">
		<beans:property name="sessionFactory"
			ref="hibernate4AnnotatedSessionFactory" />
	</beans:bean>
	<beans:bean id="reviewService"
		class="kr.ac.jbnu.jinggumdari.serviceImplementation.ReviewServiceImpl">
		<beans:property name="reviewDAO" ref="reviewDAO"></beans:property>
	</beans:bean>
	
	<beans:bean id="reviewImageDAO" class="kr.ac.jbnu.jinggumdari.DAO.ReviewImageDAOImpl">
		<beans:property name="sessionFactory"
			ref="hibernate4AnnotatedSessionFactory" />
	</beans:bean>
	<beans:bean id="reviewImageService"
		class="kr.ac.jbnu.jinggumdari.serviceImplementation.ReviewImageServiceImpl">
		<beans:property name="reviewImageDAO" ref="reviewImageDAO"></beans:property>
	</beans:bean>
	
	<beans:bean id="routeDAO" class="kr.ac.jbnu.jinggumdari.DAO.RouteDAOImpl">
		<beans:property name="sessionFactory"
			ref="hibernate4AnnotatedSessionFactory" />
	</beans:bean>
	<beans:bean id="routeService"
		class="kr.ac.jbnu.jinggumdari.serviceImplementation.RouteServiceImpl">
		<beans:property name="routeDAO" ref="routeDAO"></beans:property>
	</beans:bean>
	
	<beans:bean id="routeInfoDAO" class="kr.ac.jbnu.jinggumdari.DAO.RouteInfoDAOImpl">
		<beans:property name="sessionFactory"
			ref="hibernate4AnnotatedSessionFactory" />
	</beans:bean>
	<beans:bean id="routeInfoService"
		class="kr.ac.jbnu.jinggumdari.serviceImplementation.RouteInfoServiceImpl">
		<beans:property name="routeInfoDAO" ref="routeInfoDAO"></beans:property>
	</beans:bean>
	
	<beans:bean id="searchDAO" class="kr.ac.jbnu.jinggumdari.DAO.SearchDAOImpl">
		<beans:property name="sessionFactory"
			ref="hibernate4AnnotatedSessionFactory" />
	</beans:bean>
	<beans:bean id="searchService"
		class="kr.ac.jbnu.jinggumdari.serviceImplementation.SearchServiceImpl">
		<beans:property name="searchDAO" ref="searchDAO"></beans:property>
	</beans:bean>

	<beans:bean id="writingDAO" class="kr.ac.jbnu.jinggumdari.DAO.WritingDAOImpl">
		<beans:property name="sessionFactory"
			ref="hibernate4AnnotatedSessionFactory" />
	</beans:bean>
	<beans:bean id="writingService"
		class="kr.ac.jbnu.jinggumdari.serviceImplementation.WritingServiceImpl">
		<beans:property name="writingDAO" ref="writingDAO"></beans:property>
	</beans:bean>
	
	<tx:annotation-driven transaction-manager="transactionManager" />

	<beans:bean id="transactionManager"
		class="org.springframework.orm.hibernate4.HibernateTransactionManager">
		<beans:property name="sessionFactory"
			ref="hibernate4AnnotatedSessionFactory" />
	</beans:bean>
</beans:beans>

and what is needed more?


Answer:

first remove this line

<%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>

and this add into header tag

<meta http-equiv='Content-Type' content='text/html; charset=UTF-8' />

then add into web.xml

 <filter>
    <filter-name>encoding-filter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
       <param-name>encoding</param-name>
       <param-value>UTF-8</param-value>
    </init-param>
 </filter>
 <filter-mapping>
    <filter-name>encoding-filter</filter-name>
    <url-pattern>/*</url-pattern>
 </filter-mapping>

then add to hibernate configuration file into

<bean id="sessionFactory"
        class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
                <prop key="hibernate.connection.CharSet">utf8</prop>
                <prop key="hibernate.connection.characterEncoding">utf8</prop>
                <prop key="hibernate.connection.useUnicode">true</prop>
            </props>
        </property>

Related:


Using world coordinates


java,libgdx
I am currently using pixels as units for placing objects within my world, however this can get tedious because I only ever place objects every 16 pixels. For example, I would like to be able to place an object at position 2 and have the object rendered at the pixel...

Get document on some condition in elastic search java API


java,elasticsearch,elasticsearch-plugin
As I know we can parse document in elastic search, And when we search for a keyword, It will return the document using this code of java API:- org.elasticsearch.action.search.SearchResponse searchHits = node.client() .prepareSearch() .setIndices("indices") .setQuery(qb) .setFrom(0).setSize(1000) .addHighlightedField("file.filename") .addHighlightedField("content") .addHighlightedField("meta.title") .setHighlighterPreTags("<span class='badge badge-info'>") .setHighlighterPostTags("</span>") .addFields("*", "_source")...

@RestController throws HTTP Status 406


java,spring,rest,maven
I am working on a basic Hello World program using Spring and Restful webservices. But when I try to call my service I am getting below error message: HTTP Status 406 - description - The resource identified by this request is only capable of generating responses with characteristics not acceptable...

WebDriver can't get dropdown menu element (Java)


java,selenium,webdriver,junit4
I write a script on Java for Selenium WebDriver, and I have a problem with selected from dropdown menu. Here's my locator: new Select(driver.findElement(By.id("FormElement_select_68_input_input"))).selectByVisibleText("Image"); Here's an error: http://prntscr.com/7jul03 Here's HTML code: http://prntscr.com/7jvou6 Need to select "Image" from this menu, but have an error. Before I had the error like this,...

Android set clickable text to go one fragment to another fragment


java,android,android-fragments,spannablestring
I need to do something like this. Suppose I have 2 fragments A and B.There is a text which can be clickable in fragment A and when user click this text , he can go to fragment B. This example helped me to do it but I think it does...

Java Scanner not reading newLine after wrong input in datatype verification while loop


java,while-loop,java.util.scanner
I've looked at similar questions and tried to follow the answers that solved the issues that others have had but putting the sc.next() or sc.nextLine() after the while loop causes it to go into an infinite loop. The problem is if a user enters incorrect input (nothing or a number)...

Selenium catch popup on close browser


java,selenium,browser
I'm trying to test that when I close my window a popup shows with a warning message. I've tried both driver.close() and driver.quit() after making sure I'm on the proper window but this just terminates the process since my popup doesn't show. I could test it by using the awt...

Android String if-statement


java,android,string
I have a if-statement in the start of my app if (ready.equals("yes")){ ... } and later on my code I have ready="yes"; but the if statement is never called, why? The ready="yes"; is called from a background thread, is that why? public void DownloadFromUrl(final String fileName) { //this is the...

Bulkheading strategies for Akka actors


java,asynchronous,akka,blocking,future
I have a scenario where an important actor needs to make a call to a slow (15 - 20 seconds) remote system: // Non-actor code equivalent public Result makeSlowNetworkCall(Request request) { Result result = slowServiceClient.soooooSlow(request); // Could be up to 15 - 20 SECONDS (mehhhh) return result; } The Akka...

App Not Downloading Newest Version Of File [Java]


java,caching,download
Okay, I've been trying to figure this out for a few hours and it's starting to kill me. I wrote a primitive version checker for an app I work on every once and awhile. It's just a simple for fun project. The version checker has been a pain though. It...

How to check if an ExecutionResult is empty in Neo4j


java,neo4j
I am executing a query in neo4j using java. I don't know how to check if the execution result is empty. Here is my code. String firstquery=" start n=node(*) match(b)-[relatedto]->(n) where b.value=\""+applicationName+"\" return n"; ExecutionResult execResult = execEngine.execute(firstquery); System.out.println("executing query"); String results = execResult.dumpToString(); System.out.println(results); Iterator<Node> n_column1 = execResult.columnAs( "n"...

How to block writes to standard output in java (System.out.println())


java,logging,stdout
In Java, how to block code from writing to system out? My app calls a 3rd party library that spams logs by issuing numerous System.out.println() calls. I don't have legal rights to decompile and patch the library. I'm running Websphere 8.5.x Considered using System.setOut(PrintStream out), but that will effect the...

Javadoc: Do parameter and return need an explicit type description


java,types,javadoc
When Javadoc'ing, I don't know whether you should explicitly say whether the parameters are of type String or int. For example /** * This method does something * @param foo an object of type Foo * @param abc the number of doors, of type int * @return the number of...

Get network interfaces on remote machine


java,network-programming
I know in java we can do NetworkInterface.getNetworkInterfaces() to get all available network interfaces on local machine. Can we do similar thing where I can pass host name to get the NICs(with IPs) which are up and running?

BitmapFont class does not have getBound(String) method


java,android,libgdx
Previously I used getBound method for BitmapFont class in libgdx, but now, I am unable to use it. I cannot find the changes in latest version. Any help is appreciated. Thank you...

Get current latitude and longitude android


java,android,gps,geolocation,location
Requirement: 1.Sometimes(not everytime) I am getting latitude and longitude 0.0. 2.I want to know how to get the location update after user has enabled the gps from the settings. Here is my code public class GPSTracker extends Service implements LocationListener { private final Context mContext; // flag for GPS status...

Dynamic creation of objects vs storing them as fields


java,performance,object
I have this loop which runs about 1,000,000 times. while ((line = br.readLine()) != null) { if(!(line.isEmpty())){ data = new JSONObject(line); name = (String)data.get("name"); surname = (String)data.get("surname"); ar.put(name, surname); //an array } } What are the advantages (if any) in terms of efficiency of having it like that were data,name...

Java dice roll with unexpected random number


java,if-statement
I've written a simple Java program to display the results of 20 dice rolls on the console. The results I'm getting are listed below: 3 1 [email protected] 1 5 4 1 [email protected] 1 [email protected] [email protected] 1 6 [email protected] 1 [email protected] [email protected] 1 2 3 3 When I ran it for...

Logging operations in lightadmin


java,spring,logging,lightadmin
I have a Java web application which use Spring and Hibernate and I plan to use lightadmin to provide an administration interface. However, I found very little information about the logging part of lightadmin : if I have such an adminsitration interface, I would like that any operation made to...

Join files using Apache Spark / Spark SQL


java,apache-spark,apache-spark-sql
I am trying to use Apache Spark for comparing two different files based on some common field, and get the values from both files and write it as output file. I am using Spark SQL for joining both files (after storing the RDD as table). Is this the correct approach?...

How to call MySQL view in Struts2 or Hibernate


java,mysql,hibernate,java-ee,struts2
I have a view in MySQL database CREATE VIEW CustInfo AS SELECT a.custName, a.custMobile, b.profession, b.companyName, b.annualIncome FROM customer a INNER JOIN cust_proffessional_info b ON a.cust_id=b.cust_id Is there any way that i can call this view using Struts2 or in Hibernate. I have tried to search it but could not...

Unfortunately, (My app) has stopped. Eclipse Android [duplicate]


java,android,eclipse,adt
This question already has an answer here: What is a Null Pointer Exception, and how do I fix it? 12 answers I'm a beginner in android developing and I'm trying to build a simple app but I'm getting this error in the emulator.(Unfortunately,(App) has unexpectedly stopped). LogCat http://i.stack.imgur.com/VZhuL.png package...

count items in a column vaadin


java,vaadin
Good day everyone! How do I get the number of items that a column contains? I want to hide the "Workgroup" column if it's empty, I just don't know how. Table tblTeachings = new Table(); tblTeachings.addContainerProperty("#", Integer.class,0); tblTeachings.addContainerProperty("Course",String.class,""); tblTeachings.addContainerProperty("Teaching name",String.class,""); tblTeachings.addContainerProperty("Start date",String.class,""); tblTeachings.addContainerProperty("End Date",String.class,""); tblTeachings.addContainerProperty("Activity...

How to do custom rounding of numbers in Java?


java,rounding
Suppose I want to round numbers that have mantissa greater than 0.3 'up' and those below 'down'. How can I do it in Java? The only thing that came to my mind was Math.round(), but I can't seem to make it follow a certain rule....

Reading and modifying the text from the text file in Java


java
I am have a project that need to modify some text in the text file. Like BB,BO,BR,BZ,CL,VE-BR I need make it become BB,BO,BZ,CL,VE. and HU, LT, LV, UA, PT-PT/AR become HU, LT, LV, UA,/AR. I have tried to type some code, however the code fail to loop and also,in this...

setOnClickListener error Null object


java,android
I saw many questions like mine and I try to fix my codes but failed... this is my code: public class MainActivity extends ActionBarActivity { EditText usernameEditText; EditText passwordEditText; public Button saveme; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); usernameEditText = (EditText) findViewById(R.id.username); passwordEditText = (EditText) findViewById(R.id.pass); saveme = (Button)...

Form submit portlet with Spring MVC


java,jsp,spring-mvc,liferay,portlet
I'm trying to achieve a Liferay portlet of submit form using spring MVC. The model: package com.model; public class Person { String firstName; String middleName; public String getFirstName() { return this.firstName; } public String getMiddleName() { return this.middleName; } public void setFirstName(String firstName) { this.firstName=firstName; } public void setMiddleName(String middleName)...

error: cannot find symbol class AsyncCallWS Android


java,android,web-services
I'm trying to rewrite the application in this, in Android Studio link, which is written in Eclipse. There are two problems, first problem is there is this line in the project : import com.example.webserviceactivity.R; I couldn't write this one on Android Studio. The second problem is, in this part of...

Finding embeded xpaths in a String


java,regex
I have a string where I have the user should be able to specify xpaths that will be evaluated at runtime. I was thinking about having a the following way to specify it. String = "Hi my name is (/message/user) how can i help you with (/message/message) "; How can...

why java API prevents us to call add and remove together?


java,list,collections,listiterator
As per Java API- IllegalStateException - if neither next nor previous have been called, or remove or add have been called after the last call to next or previous remove()- Removes from the list the last element that was returned by next() or previous() (optional operation). This call can only...

how to call Java method which returns any List from R Language? [on hold]


java,r,rjava
How to call java method which returns list from R Language.

Getting particular view from expandable listview


java,android,listview,android-fragments,expandablelistview
In my list view I have an textview in expandable group and I want to open the dialog when textview is clicked to fill the information through edittext and update textview. Problem: how could I get the groupview textview item in my fragment oncreateview() method....

type conversion if flex


java,actionscript-3,flex
I am using Flerry as Java-Flex bridge for my Flex Desktop Application. How to convert List in Java to ArrayCollection in Flex Flex Code:- [Bindable]public var screenList:ArrayCollection; <flerry:NativeObject id="windowControllerObj" source="ls.window.EnumAllWindowNames" singleton="true" fault="windowControllerObj_faultHandler(event)"> <flerry:NativeMethod id="getWindowNames" name="getAllWindowNames" result="windowControllerObj_resultHandler(event)" fault="getWindowNames_faultHandler(event)"/>...

Trouble with Login using Spring Boot and JDBC Security


spring,spring-security,spring-boot
My build.gradle file: task wrapper(type: Wrapper) { gradleVersion = '2.4' } buildscript { repositories { mavenCentral() maven { url "http://repo.spring.io/release" } } dependencies { classpath("org.springframework.boot:spring-boot-gradle-plugin:1.2.3.RELEASE") } } apply plugin: 'java' apply plugin: 'spring-boot' repositories { mavenCentral() maven { url "http://repo.spring.io/release" } } dependencies { compile("org.springframework.boot:spring-boot-starter-web") compile("org.springframework.boot:spring-boot-starter-jdbc")...

custom arraylist get distinct


java,android
is there any way to get the distinct values of a custom arraylist? public class mystatistic extends BaseActivity { public String objectid; public String playerid; public String playername; public String enemyid; public String enemyname; public String question; public mystatistik(String objectid, String playerid, String playername, String enemyid, String enemyname, String question)...

Numeric literals in Java - octal? [duplicate]


java,literals,octal
This question already has an answer here: How does a leading zero change a numeric literal in Java? 3 answers Here is some code in java on datatypes: class Test { public static void main(String args[]) { int i = -0777; System.out.println(i); } } The output of the above...

Get the value of the last inserted record


java,jdbc
I am trying to get the stop_name of the last inserted row in the table with preparedStatement. How can I get the last inserted one? I appreciate any help. behavoiur table: CREATE TABLE IF NOT EXISTS behaviour( behaviour_id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY, mac VARCHAR(30) NOT NULL, stop_name VARCHAR(30)...

Interpreting hex dump of java class file


java,class,hex
I understand the structure of a java .class file, but when I want to interpret the raw hex data I get a bit lost. This is a hex dump of a class file, excluding the header and constant pool. I understand the header to be the magic number, minor_version and...

Mysterious claim of a missing { in eclipse


java,eclipse
I have a case of a mysterious missing curly brace that I don't see any use for. Eclipse says, "Syntax error on token ";", { expected after this token". Either I am missing something very silly or there is something new I have to learn about Java. This is the...

Can I install 2 or more Android SDK when using Eclipse


java,android,eclipse,sdk,versions
I am new to android developments. I am setting up my android development environment using Eclipse. I have a test smart phone with Android version 4.2.2. The automatic installation installed the latest Android SDK version, which is 5.1.1. My questions are: 1. Do I have to install the SDK version...

viewResolver with more folders inside of WEB-INF/jsp is not working in spring


java,spring,jsp,spring-mvc
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> <!-- avoid '???' --> <property name="prefix" value="/WEB-INF/jsp/" /> <property name="suffix" value=".jsp"/> </bean> if i create other subfolders under jsp , for instance /WEB-INF/jsp/reports , /WEB-INF/jsp/insertions how should i configure now the viewResolver to can resolve these new sub folders??...

How can implement long running process in spring hibernate?


java,spring,hibernate
as we know the struts interceptor execute and wait will take care of long running process by not getting the request to timeout and destroy it sends wait and at last the desired response i want to implement the same for long running process in spring and hibernate. Thanks....

Get element starting with letter from List


java,android,list,indexof
I have a list and I want to get the position of the string which starts with specific letter. I am trying this code, but it isn't working. List<String> sp = Arrays.asList(splited); int i2 = sp.indexOf("^w.*$"); ...

Android Implicit Intent for Viewing a Video File


java,android,android-intent,uri,avd
In my Android app, I have a button that when clicked, launches the external application of my choice to play a video (I gather that this is called an "implicit intent"). Here is the relevant Java code from my onCreate method. Button button = (Button) findViewById(R.id.button); button.setOnClickListener ( new Button.OnClickListener()...

PropertyNotFoundException in jsp


java,jsp
Am getting this error in my application javax.el.PropertyNotFoundException: Property 'survey_id' not found on type com.moh.forms.MOH731 javax.el.BeanELResolver$BeanProperties.get(BeanELResolver.java:229) javax.el.BeanELResolver$BeanProperties.access$400(BeanELResolver.java:206) javax.el.BeanELResolver.property(BeanELResolver.java:317) javax.el.BeanELResolver.getValue(BeanELResolver.java:85) This is my MOH731.java @Id @GeneratedValue(strategy = GenerationType.AUTO) private int survey_id; public MOH731 (int survey_id, String uname)...

SOAP Client, Following an example


java,soap,saaj
I need to consume a SOAP Server named "Mouser" for my company. However I have a problem when I try to send a message. The documentation of my request is : POST /service/searchapi.asmx HTTP/1.1 Host: www.mouser.fr Content-Type: application/soap+xml; charset=utf-8 Content-Length: length <?xml version="1.0" encoding="utf-8"?> <soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope"> <soap12:Header> <MouserHeader...