mercredi 6 mai 2015

how to take the greatest integer and if are 2 or more take one randomly

my code

int zone1;
int zone2;
int zone3;


public void countVotes()
{
if ((zone1 == 0) && (zone2 == 0) && (zone3 == 0))
        {               
            return;
        }
        if ((zone1 == zone2) && (zone2 == zone3))
        {
            newzone = Rnd.get(1, 3);
            return;
        }
        if ((zone2 < zone1) && (zone1 > zone3))
        {
            newzone = 1;
        }
        if ((zone1 < zone2) && (zone2 > zone3))
        {
            newzone = 2;
        }
        if ((zone1 < zone3) && (zone3 > zone2))
        {
            newzone = 3;
        }
        changeZone(newzone);
}

and is not what I exactly want, how to simple take grater integer? i cannot imagine that if i will want add more zones ;/

How to create Bullet Square in Word POI Java [on hold]

I dealt the creation of a document . I used the API POI to create the document in Word format. It can help you to create lists. You have best solutions? Thanks!!

This is my solution:

public class SetBulletSquareWordPOI {
    private static String FILE_DOC = "C:/Temp/Test1.doc";
    public static void main(String[] args) throws Exception {
        XWPFDocument doc = new XWPFDocument();
        XWPFParagraph para = doc.createParagraph();
        para.setVerticalAlignment(TextAlignment.CENTER);
        XWPFRun run = para.createRun();
        //Character Square
        run.setText(String.valueOf((char) 110));
        // Font importatnte for display
        run.setFontFamily("Wingdings");
        run.setFontSize(6);
        run = para.createRun();
        run.setText(" Forza Roma");
        run.setFontFamily("Verdana");
        run.setFontSize(10);
        try(FileOutputStream out = new FileOutputStream(FILE_DOC)){
            doc.write(out);
        }
    }
}

Set event_scheduler in mysql

I am trying to set the event to on for the bus table but it does not work. The table as well as the event is being created but the event is not being triggered. I have already set this line event_scheduler = ON; in mysql- my.ini and restart the server.

    // Create bus table
    stt.execute("CREATE TABLE IF NOT EXISTS bus"
            + "(id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,"
            + "mac VARCHAR(30) NOT NULL UNIQUE,"
            + "route int(11) NOT NULL,"
            + "latitude FLOAT(10,6) NOT NULL,"
            + "longitude FLOAT(10,6) NOT NULL,"
            + "created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)");

    stt.execute("CREATE EVENT IF NOT EXISTS  AutoDelete "
            + "ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL 3 MINUTE "
            + "DO "
            + "DELETE FROM bus WHERE created_at < (NOW() - INTERVAL 3 MINUTE)");
    stt.execute("SET GLOBAL event_scheduler = ON");

How can I improve/optimize my program with ExecutorService?

So, I'm new in Java.

I wrote relatively simple program that does something with a lot of files.

It was slow, I wanted to run more threads than one. With little StackOverflow Community help I made something like this:

public class FileProcessor {
    public static void main(String[] args)
    {
        // run 5 threads
        ExecutorService executor = Executors.newFixedThreadPool(5);
        int i;

        // get first and last file ID to process
        int start = Integer.parseInt(args[0]);
        int end = Integer.parseInt(args[1]);

        for (i = start; i < end; i++)
        {
            final int finalId = i; // final necessary in anonymous class
            executor.submit(new Runnable() 
            {
                public void run() 
                {
                    processFile(finalId);
                }
            });
        }
    }

    public static void processFile(int id)
    {
        //doing work here
    }
}

This is really really simple multithreading solution and it does what I want. Now I want to improve it.

  1. Shall I reduce number of Runnable objects existing in memory at the same time? If I should - how can I do it?

  2. How can I detect, that all job is done and exit program (and threads)?

Most eficient way to count occurences?

I've got an array of bytes (primitive), they can have random values. I'm trying to count occurences of them in the array in the most eficient/fastest way. Currently I'm using:

HashMap<Byte, Integer> dataCount = new HashMap<>();
for (byte b : data) dataCount.put(b, dataCount.getOrDefault(b, 0) + 1);

This one-liner takes ~500ms to process a byte[] of length 24883200. Using a regular for loop takes at least 600ms.

I've been thinking of constructing a set (since they only contain one of each element) then adding it to a HashMap using Collections.frequency(), but the methods to construct a Set from primitives require several other calls, so I'm guessing it's not as fast.

What would be the fastest way to accomplish counting of occurences of each item?

I'm using Java 8 and I'd prefer to avoid using Apache Commons if possible.

HBase Mapreduce job compiles but breaks when running

I have a project that is successfully implementing mapreduce jobs. But I am now trying to add in another job that pulls data from HBase. The project compiles just fine but when I try to run the job I get java.lang.NoSuchMethodError: org.apache.hadoop.mapreduce.Job.addFileToClassPath(Lorg/apache/hadoop/fs/Path;)V See the code at the bottom for the full stack trace. I have been able to narrow it down to maven dependencies, but I can't find what the issue is. The only dependency I have added is

    <dependency>
            <groupId>org.apache.hbase</groupId>
            <artifactId>hbase-server</artifactId>
            <version>0.98.6-cdh5.3.2</version>
            <exclusions>
                <exclusion>
                    <artifactId>jasper-compiler</artifactId>
                    <groupId>tomcat</groupId>
                </exclusion>
                <exclusion>
                    <artifactId>jasper-runtime</artifactId>
                    <groupId>tomcat</groupId>
                </exclusion>
                <exclusion>
                    <groupId>org.mortbay.jetty</groupId>
                    <artifactId>jsp-2.1</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

The full pom.xml is found below. What is conflicting? I can't find the maven dependency that the org.apache.hadoop.mapreduce.Job depends on, but anytime I try to add a dependency it breaks the compile like I have duplicate dependencies. EDIT: I have found that the dependency is being inherited from another class, which is why the duplicate dependency is being made. It seems like the hadoop-mapreduce-client-core jar is not being included at run time, but there is no scope on it, and I have confirmed that it is in the buildpath.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://ift.tt/IH78KX" xmlns:xsi="http://ift.tt/ra1lAU" xsi:schemaLocation="http://ift.tt/IH78KX http://ift.tt/VE5zRx">
    <parent>
        <artifactId>parent-project</artifactId>
        <groupId>com.project</groupId>
        <version>HEAD-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>this-project</artifactId>
    <packaging>jar</packaging>

    <properties>
        <org.springframework-version>4.1.5.RELEASE</org.springframework-version>
        <spring.batch.version>3.0.0.RELEASE</spring.batch.version>
    </properties>

    <build>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <dependencies>
        <dependency>
            <groupId>com.project</groupId>
            <artifactId>custom-library/artifactId>
            <version>HEAD-SNAPSHOT</version>
            <exclusions>
                <exclusion>
                    <artifactId>log4j</artifactId>
                    <groupId>log4j</groupId>
                </exclusion>
                <exclusion>
                    <artifactId>slf4j-jcl</artifactId>
                    <groupId>org.slf4j</groupId>
                </exclusion>
                <exclusion>
                    <artifactId>slf4j-log4j12</artifactId>
                    <groupId>org.slf4j</groupId>
                </exclusion>
                <exclusion>
                    <artifactId>javax.servlet</artifactId>
                    <groupId>org.glassfish</groupId>
                </exclusion>
                <exclusion>
                    <artifactId>juel-impl</artifactId>
                    <groupId>de.odysseus.juel</groupId>
                </exclusion>
                <exclusion>
                    <artifactId>servlet-api</artifactId>
                    <groupId>javax.servlet</groupId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.apache.hadoop</groupId>
            <artifactId>hadoop-common</artifactId>
            <version>2.5.0-cdh5.3.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.hadoop</groupId>
            <artifactId>hadoop-hdfs</artifactId>
            <version>2.5.0-cdh5.3.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.hadoop</groupId>
            <artifactId>hadoop-yarn-client</artifactId>
            <version>2.5.0-cdh5.3.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.hadoop</groupId>
            <artifactId>hadoop-client</artifactId>
            <version>2.5.0-cdh5.3.2</version>
        </dependency>
        <dependency>
            <groupId>com.hadoop.gplcompression</groupId>
            <artifactId>hadoop-lzo</artifactId>
            <version>0.4.15-gplextras5.0.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.maven.plugin-tools</groupId>
            <artifactId>maven-plugin-annotations</artifactId>
            <version>3.3</version>
        </dependency>
        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib</artifactId>
            <version>2.2.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.hbase</groupId>
            <artifactId>hbase-client</artifactId>
            <version>0.98.6-cdh5.3.2</version>
            <exclusions>
                <exclusion>
                    <groupId>org.apache.hadoop</groupId>
                    <artifactId>hadoop-core</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.apache.hbase</groupId>
            <artifactId>hbase-protocol</artifactId>
            <version>0.98.6-cdh5.3.2</version>
            <exclusions>
                <exclusion>
                    <artifactId>jasper-compiler</artifactId>
                    <groupId>tomcat</groupId>
                </exclusion>
                <exclusion>
                    <artifactId>jasper-runtime</artifactId>
                    <groupId>tomcat</groupId>
                </exclusion>
                <exclusion>
                    <groupId>org.mortbay.jetty</groupId>
                    <artifactId>jsp-2.1</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.apache.hbase</groupId>
            <artifactId>hbase-server</artifactId>
            <version>0.98.6-cdh5.3.2</version>
            <exclusions>
                <exclusion>
                    <artifactId>jasper-compiler</artifactId>
                    <groupId>tomcat</groupId>
                </exclusion>
                <exclusion>
                    <artifactId>jasper-runtime</artifactId>
                    <groupId>tomcat</groupId>
                </exclusion>
                <exclusion>
                    <groupId>org.mortbay.jetty</groupId>
                    <artifactId>jsp-2.1</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.apache.zookeeper</groupId>
            <artifactId>zookeeper</artifactId>
            <version>3.4.5-cdh5.3.2</version>
            <exclusions>
                <exclusion>
                    <artifactId>jasper-compiler</artifactId>
                    <groupId>tomcat</groupId>
                </exclusion>
                <exclusion>
                    <artifactId>jasper-runtime</artifactId>
                    <groupId>tomcat</groupId>
                </exclusion>
                <exclusion>
                    <groupId>org.mortbay.jetty</groupId>
                    <artifactId>jsp-2.1</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.apache.hadoop</groupId>
            <artifactId>hadoop-yarn-api</artifactId>
            <version>2.6.0</version>
            <exclusions>
                <exclusion>
                    <artifactId>jasper-compiler</artifactId>
                    <groupId>tomcat</groupId>
                </exclusion>
                <exclusion>
                    <artifactId>jasper-runtime</artifactId>
                    <groupId>tomcat</groupId>
                </exclusion>
                <exclusion>
                    <groupId>org.mortbay.jetty</groupId>
                    <artifactId>jsp-2.1</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>
</project>


Error when trying to hit endpoint with Postman:

    <html>
    <head>
        <title>Apache Tomcat/7.0.57 - Error report</title>
    </head>
    <body>
        <h1>HTTP Status 500 - Handler processing failed; nested exception is java.lang.NoSuchMethodError: org.apache.hadoop.mapreduce.Job.addFileToClassPath(Lorg/apache/hadoop/fs/Path;)V</h1>
        <HR size="1" noshade="noshade">
            <p>
                <b>type</b> Exception report
            </p>
            <p>
                <b>message</b>
                <u>Handler processing failed; nested exception is java.lang.NoSuchMethodError: org.apache.hadoop.mapreduce.Job.addFileToClassPath(Lorg/apache/hadoop/fs/Path;)V</u>
            </p>
            <p>
                <b>description</b>
                <u>The server encountered an internal error that prevented it from fulfilling this request.</u>
            </p>
            <p>
                <b>exception</b>
                <pre>org.springframework.web.util.NestedServletException: Handler processing failed; nested exception is java.lang.NoSuchMethodError: org.apache.hadoop.mapreduce.Job.addFileToClassPath(Lorg/apache/hadoop/fs/Path;)V
    org.springframework.web.servlet.DispatcherServlet.triggerAfterCompletionWithError(DispatcherServlet.java:1287)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:961)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:877)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966)
    org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:868)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:646)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
    org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
</pre>
            </p>
            <p>
                <b>root cause</b>
                <pre>java.lang.NoSuchMethodError: org.apache.hadoop.mapreduce.Job.addFileToClassPath(Lorg/apache/hadoop/fs/Path;)V
    com.project.module.basic.util.MapredJobUtil.setExternalHdfsJobPaths(MapredJobUtil.java:107)
    com.project.module.basic.driver.MapredDriver.setExternalHdfsJobPaths(MapredDriver.java:89)
    com.project.module.basic.driver.MapredDriver.setStandardMapredJob(MapredDriver.java:79)
    com.project.module.basic.driver.BasicProcessDriver.setup(BasicProcessDriver.java:46)
    com.project.module.process.service.impl.processConfigService.setupProcess(ProcessConfigService.java:79)
    com.project.module.process.service.impl.processConfigService$$FastClassBySpringCGLIB$$7c1056d6.invoke(&lt;generated&gt;)
    org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
    org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:649)
    com.project.module.process.service.impl.processServiceImpl.setupprocess(processServiceImpl.java:102)
    com.project.module.process.service.impl.processServiceImpl.runprocess(processServiceImpl.java:56)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    java.lang.reflect.Method.invoke(Method.java:606)
    org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
    org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
    org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
    org.springframework.cache.interceptor.CacheInterceptor$1.invoke(CacheInterceptor.java:52)
    org.springframework.cache.interceptor.CacheAspectSupport.invokeOperation(CacheAspectSupport.java:317)
    org.springframework.cache.interceptor.CacheAspectSupport.execute(CacheAspectSupport.java:350)
    org.springframework.cache.interceptor.CacheAspectSupport.execute(CacheAspectSupport.java:299)
    org.springframework.cache.interceptor.CacheInterceptor.invoke(CacheInterceptor.java:61)
    org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
    com.sun.proxy.$Proxy83.runprocess(Unknown Source)
    com.project.module.process.controller.impl.processControllerImpl.runprocess(processControllerImpl.java:28)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    java.lang.reflect.Method.invoke(Method.java:606)
    org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
    org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
    org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:777)
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:706)
    org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:943)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:877)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966)
    org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:868)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:646)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
    org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
</pre>
            </p>
            <p>
                <b>note</b>
                <u>The full stack trace of the root cause is available in the Apache Tomcat/7.0.57 logs.</u>
            </p>
            <HR size="1" noshade="noshade">
                <h3>Apache Tomcat/7.0.57</h3>
            </body>
        </html>

Syntax error, delete token "else"

public class Basic {

    public static void main (String []args){
        int first = 1;
            if (first == 1);{ 
                System.out.println("I did it");
            } 
            else {
                System.out.println("I didnt do it");
            }

I dont know what to do, is there a mistake and i followed all the steps in the tutorials i'm watching. It just says delete the token

Java program termination in Windows vs Linux console (Ctrl-C not working under windows)

I wrote simple console Java program. It uses ExecutorService and it runs few threads.

I'm using it under Windows and Linux.

I can terminate it with CTRL+C under Linux, but it doesn't work under Windows.

Can I "fix" this somehow in my program? (without changes in OS configuration or Java Runtime configuration).

I'm using JDK 1.8 / JRE 1.8.

RMI java, how to "remotely"

I just "created" a Client-Server Java RMI on the same java virtual machine(it's a trivial thing an RMI on the same machine). I want to use a Client-Server RMI remotely. I'll use two machines: the first, called A, will be the Server; the second, called B, will be the client. So I want to know which are the differents beewten remotely and locally RMI Client-Server. For example, on machine A:

  1. I write the code for the RemoteInterface extends Remote;
  2. I write the code for the class of real remote object:

    public class RemoteObj extends UnicastRemoteObject implements RemoteInterface
    
    
  3. I write the code for the server side which I bind the remoteObj using the IP of the machine A on the neetwork

    public class Server {
    ............
    RemoteObj obj = new RemoteObj();
    String globalName = "rmi//IP_machine_A/hello";
    Naming.rebind(globalName, obj);
    
    
  4. I use the rmic RemoteObj command to auto generate the stub

  5. I use the start rmiregistry command to start RMI registry server
  6. Finally I must start the server

On the machine B, instead:

  1. I write the code for Client, which I lookup the rmi registry with the global name:

     public class Client {
     .......
     String globalName = "rmi//IP_machine_A/hello";
     RemoteInterface remoteObj = (RemoteInterface)Naming.lookup(globalName);
    
    
  2. I must start the client

Are these statementes correct? Thanks guy

PostgreSQL with Hibernate not persisting my Entity

I'm building an application with Hibernate and PostgreSQL.

but when I call the persist(entity) method, nothing appears on my table.

my persistence.xml:

<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://ift.tt/1cKbVbQ"
    xmlns:xsi="http://ift.tt/ra1lAU"
    xsi:schemaLocation="http://ift.tt/1cKbVbQ
    http://ift.tt/1kMb4sd"
    version="2.1">
    <persistence-unit name="myPersistenceUnit">
        <provider>org.hibernate.ejb.HibernatePersistence</provider>
        <!-- Annotated entity classes -->
        <class>br.com.programadoremjava.MyEntity</class>
        <properties>
            <property name="hibernate.connection.url" value="jdbc:postgresql://localhost/netshoes" />
            <property name="hibernate.connection.driver_class" value="org.postgresql.Driver" />
            <property name="hibernate.connection.username" value="postgres" />
            <property name="hibernate.connection.password" value="admin" />
            <property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect" />
            <property name="hibernate.hbm2ddl.auto" value="create" />
        </properties>
    </persistence-unit>
</persistence>

my persistMethod:

public void persist(MyEntity myEntity) {
    Persistence.createEntityManagerFactory("myPersistenceUnit")
    .createEntityManager().persist(myEntity);
}

my log output:

14:05:10,122 INFO  [org.hibernate.Version] (http-localhost/127.0.0.1:80-1) HHH000412: Hibernate Core {4.3.9.Final}
14:05:10,135 INFO  [org.hibernate.cfg.Environment] (http-localhost/127.0.0.1:80-1) HHH000206: hibernate.properties not found
14:05:10,140 INFO  [org.hibernate.cfg.Environment] (http-localhost/127.0.0.1:80-1) HHH000021: Bytecode provider name : javassist
14:05:10,440 INFO  [org.hibernate.annotations.common.Version] (http-localhost/127.0.0.1:80-1) HCANN000001: Hibernate Commons Annotations {4.0.5.Final}
14:05:10,515 WARN  [org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl] (http-localhost/127.0.0.1:80-1) HHH000402: Using Hibernate built-in connection pool (not for production use!)
14:05:10,515 INFO  [org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl] (http-localhost/127.0.0.1:80-1) HHH000401: using driver [org.postgresql.Driver] at URL [jdbc:postgresql://localhost/netshoes]
14:05:10,515 INFO  [org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl] (http-localhost/127.0.0.1:80-1) HHH000046: Connection properties: {user=postgres, password=****}
14:05:10,515 INFO  [org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl] (http-localhost/127.0.0.1:80-1) HHH000006: Autocommit mode: false
14:05:10,515 INFO  [org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl] (http-localhost/127.0.0.1:80-1) HHH000115: Hibernate connection pool size: 20 (min=1)
14:05:11,078 INFO  [org.hibernate.dialect.Dialect] (http-localhost/127.0.0.1:80-1) HHH000400: Using dialect: org.hibernate.dialect.PostgreSQLDialect
14:05:11,104 INFO  [org.hibernate.engine.jdbc.internal.LobCreatorBuilder] (http-localhost/127.0.0.1:80-1) HHH000424: Disabling contextual LOB creation as createClob() method threw error : java.lang.reflect.InvocationTargetException
14:05:11,294 INFO  [org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory] (http-localhost/127.0.0.1:80-1) HHH000397: Using ASTQueryTranslatorFactory
14:05:11,824 INFO  [org.hibernate.tool.hbm2ddl.SchemaExport] (http-localhost/127.0.0.1:80-1) HHH000227: Running hbm2ddl schema export
14:05:11,889 WARN  [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (http-localhost/127.0.0.1:80-1) SQL Warning Code: 0, SQLState: 00000
14:05:11,891 WARN  [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (http-localhost/127.0.0.1:80-1) análise de S_3: COMMIT
14:05:11,893 WARN  [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (http-localhost/127.0.0.1:80-1) SQL Warning Code: 0, SQLState: 00000
14:05:11,894 WARN  [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (http-localhost/127.0.0.1:80-1) StartTransactionCommand
14:05:11,896 WARN  [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (http-localhost/127.0.0.1:80-1) SQL Warning Code: 0, SQLState: 00000
14:05:11,897 WARN  [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (http-localhost/127.0.0.1:80-1) ligação de <unnamed> para S_3
14:05:11,899 WARN  [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (http-localhost/127.0.0.1:80-1) SQL Warning Code: 0, SQLState: 00000
14:05:11,900 WARN  [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (http-localhost/127.0.0.1:80-1) executar S_3: COMMIT
14:05:11,902 WARN  [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (http-localhost/127.0.0.1:80-1) SQL Warning Code: 0, SQLState: 00000
14:05:11,903 WARN  [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (http-localhost/127.0.0.1:80-1) ProcessUtility
14:05:11,905 WARN  [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (http-localhost/127.0.0.1:80-1) SQL Warning Code: 0, SQLState: 00000
14:05:11,906 WARN  [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (http-localhost/127.0.0.1:80-1) CommitTransactionCommand
14:05:11,908 WARN  [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (http-localhost/127.0.0.1:80-1) SQL Warning Code: 0, SQLState: 00000
14:05:11,909 WARN  [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (http-localhost/127.0.0.1:80-1) CommitTransaction
14:05:11,910 WARN  [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (http-localhost/127.0.0.1:80-1) SQL Warning Code: 0, SQLState: 00000
14:05:11,912 WARN  [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (http-localhost/127.0.0.1:80-1) name: unnamed; blockState:           END; state: INPROGR, xid/subid/cid: 0/1/0, nestlvl: 1, children: 
14:05:11,914 WARN  [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (http-localhost/127.0.0.1:80-1) SQL Warning Code: 0, SQLState: 00000
14:05:11,915 WARN  [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (http-localhost/127.0.0.1:80-1) CommitTransaction
14:05:11,917 WARN  [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (http-localhost/127.0.0.1:80-1) SQL Warning Code: 0, SQLState: 00000
14:05:11,918 WARN  [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (http-localhost/127.0.0.1:80-1) name: unnamed; blockState:       STARTED; state: INPROGR, xid/subid/cid: 0/1/0, nestlvl: 1, children: 
14:05:12,028 INFO  [org.hibernate.tool.hbm2ddl.SchemaExport] (http-localhost/127.0.0.1:80-1) HHH000230: Schema export complete
14:08:31,775 INFO  [org.jboss.ejb.client] (http-localhost/127.0.0.1:443-1) JBoss EJB Client version 1.0.25.Final-redhat-1

What am I missing? Why the entity don't persist in postgres?

Can someone help me?

Division of set into two sets having same sum [on hold]

I want to design a program which demands that suppose we are given a array/set of natural numbers , now we want to find all the pair of subsets having equal sum.

Date parsing exception when in the Brazilian DST period

When entering the brazilian DST time period, the clocks are forward 1 hour. In 2014, DST began at 19/10, so the time 19/10/2014 00:00:00 became 19/10/2015 at 01:00:00. The period between "does not exist".

Because of this, when parsing the date "19/10/2014 00:45:00" using the timezone America/Sao_Paulo, it's thrown a parsing exception: java.text.ParseException: Unparseable date: "19/10/2014 00:45:00".

String date = "19/10/2014 00:59:00";
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
sdf.setLenient(false);
sdf.setTimeZone("America/Sao_Paulo");

Calendar calendar = Calendar.getInstance();
calendar.setTimeZone("America/Sao_Paulo");
calendar.setTime(sdf.parse(date));

America/Sao_Paulo timezone supposedly supports DST changes. What is the expected fix for this problem? I must change manually the jvm timezone when the DST period starts and ends? Currently the "fix" is changing the jvm timezone to GMT-2 when the DST period starts.

Note: This issue originated in an application developed with spring. The example date was throwing exception when it was being converted to a java.util.Calendar from a String. In the example code above, I set lenient to false in order to be able to reproduce the error.

Apache commons config: Generate configuration file from defaults

I want to distribute my application in one jar. That means that I do not want to ship any external files with it, that also includes that I do not want to ship the default configuration file with my project.

I could for sure build the basic XML structure with a implementation of JDOM2 or copy it out of the classpath onto the file system, but is there a out-of-the-box variant implemented by Commons Configuration?

I have only found online documentation that explains reading and handling already existing configuration files.

I would imagine this code taking in a number of Key -> Value Pairs and then generating a new config, is this possible?

Please do not offer me any alternatives to a XML file, please answer this question specifically to the implementation I asked about. If you know about any, you can suggest a alternative to Commons Configuration that does what I need to do.

Error when creating a list of objects - NullPointerException

This should be something fairly simple but I can't figure out my error. First up I am trying to write a program which will take user input and add the input as an object to a list called aList. I have two classes one called Group and one called ListObject.

Here is the Group class code

public class Group
{

   public List<Object> aList;


   public Group()
   {
      super();

      List<Object> aList = new ArrayList();

   }
 public void addToList(Object aName)
   {
       aList.add(aName);     

   } 
}

Here is my ListObject class

public class ListObject
{

    private String name;
    public int value;

    /**
     * Constructor
     */
    public ListObject(String aName)
    {
       super();
       this.name = aName;
       this.value = -1;            
    }
}

I need the method in the Group class to take user input, create an object of that name and then add it to the list aList and have all objects in that list be assigned as value of -1 to begin with. For some reason I am being returned a NullPopinterException. Hopefully you can point out what I've missed. Please note I did have this working when I was just adding strings instead of instances of the ListObject Objects.

Why can't I create a generic array in Java?

Well, I have read a lot of answers to this question, but I have a more specific one. Take the following snippet of code as an example.

public class GenericArray<E>{
    E[] s= new E[5];
}

After type erasure, it becomes

public class GenericArray{
    Object[] s= new Object[5];
}

This snippet of code seems to work well. Why does it cause a compile-time error?

In addition, I have known from other answers that the following codes work well for the same purpose.

public class GenericArray<E>{
    E[] s= (E[])new Object[5];
}

I've read some comments saying that the piece of code above is unsafe, but why is it unsafe? Could anyone provide me with a specific example where the above piece of code causes an error?

Here is my DAO:

public ReportType getByName(String type) {
    EntityManager em = emf.createEntityManager();
    try {
        ReportType rptype2 = em.find(ReportType.class, type);

        return rptype2;
    } catch (Exception e) {
        e.printStackTrace();
        em.close();
    }
    return null;
}

Here is my Action:

ReportDAO dao = new ReportDAO();
    List<ReportType> reportType = dao.show();
    list = new ArrayList<>();
    for (ReportType reportType1 : reportType) {
        list.add(reportType1.getName());
    }
    ReportTypeDAO rpDAO = new ReportTypeDAO();
    reporttype = rpDAO.getByName(type);

Here is my jsp:

 <h3>Type: <s:select list="list" name="type"></s:select>

Here is my table:

CREATE TABLE [dbo].[Report_Type](
[id] [int] IDENTITY(1,1) NOT NULL,
[name] [nvarchar](100) NULL,

When i submit, i receive a record in String format (Name), but i want to get this record ID. Is there any solution?

Thank you.

Spring/Java org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [C:\launchCodeFiles\src\main\java\RunMario.java]

I am learning Java and told to learn Spring. I am writing a simple program and get this error message (I am using IntelliJ Idea IDE):

first line of main
2015-05-06 11:37:38 INFO  ClassPathXmlApplicationContext:510 -   Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@1e717c2: startup date [Wed May 06 11:37:38 CDT 2015]; root of context hierarchy
2015-05-06 11:37:38 INFO  XmlBeanDefinitionReader:317 - Loading XML bean definitions from class path resource [ApplicationContext.xml]
2015-05-06 11:37:39 WARN  ClassPathXmlApplicationContext:487 - Exception encountered during context initialization - cancelling refresh attempt
Exception in thread "main" org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [C:\launchCodeFiles\src\main\java\RunMario.java] for bean with name 'obstacle1' defined in class path resource [ApplicationContext.xml]; nested exception is java.lang.ClassNotFoundException: C:\launchCodeFiles\src\main\java\RunMario.java
org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [C:\launchCodeFiles\src\main\java\RunMario.java] for bean with name 'obstacle1' defined in class path resource [ApplicationContext.xml]; nested exception is java.lang.ClassNotFoundException: C:\launchCodeFiles\src\main\java\RunMario.java
at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1328)
at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1328)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.determineTargetType(AbstractAutowireCapableBeanFactory.java:622)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.determineTargetType(AbstractAutowireCapableBeanFactory.java:622)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.predictBeanType(AbstractAutowireCapableBeanFactory.java:591)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.predictBeanType(AbstractAutowireCapableBeanFactory.java:591)
at org.springframework.beans.factory.support.AbstractBeanFactory.isFactoryBean(AbstractBeanFactory.java:1397)
at org.springframework.beans.factory.support.AbstractBeanFactory.isFactoryBean(AbstractBeanFactory.java:1397)
at org.springframework.beans.factory.support.AbstractBeanFactory.isFactoryBean(AbstractBeanFactory.java:968)
at org.springframework.beans.factory.support.AbstractBeanFactory.isFactoryBean(AbstractBeanFactory.java:968)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:735)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:735)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
at RunMario.main(RunMario.java:17)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at RunMario.main(RunMario.java:17)
at java.lang.reflect.Method.invoke(Method.java:497)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
Caused by: java.lang.ClassNotFoundException: C:\launchCodeFiles\src\main\java\RunMario.java
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.reflect.Method.invoke(Method.java:497)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
Caused by: java.lang.ClassNotFoundException: C:\launchCodeFiles\src\main\java\RunMario.java
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at org.springframework.util.ClassUtils.forName(ClassUtils.java:249)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at org.springframework.beans.factory.support.AbstractBeanDefinition.resolveBeanClass(AbstractBeanDefinition.java:395)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at org.springframework.beans.factory.support.AbstractBeanFactory.doResolveBeanClass(AbstractBeanFactory.java:1349)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1320)
at org.springframework.util.ClassUtils.forName(ClassUtils.java:249)
... 15 more
at org.springframework.beans.factory.support.AbstractBeanDefinition.resolveBeanClass(AbstractBeanDefinition.java:395)
at org.springframework.beans.factory.support.AbstractBeanFactory.doResolveBeanClass(AbstractBeanFactory.java:1349)
at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1320)
... 15 more

Process finished with exit code 1

My ApplicationContext.eml file is as follows.

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://ift.tt/GArMu6"
   xmlns:xsi="http://ift.tt/ra1lAU"
   xsi:schemaLocation="http://ift.tt/GArMu6
                       http://ift.tt/QEDs1e">

    <bean id="obstacle1" class="C:\launchCodeFiles\src\main\java\RunMario.java">
    <constructor-arg name= "marioObstacles" ref="obstacle"/>
    </bean>

    <bean id="obstacle" class="C:\launchCodeFiles\src\main\java\MarioObstacles.java">
    <constructor-arg name="obstacle" value="0"/>
    </bean>

</beans>

I copied and pasted the RunMario class file path from the project panel so it should be the fully qualified path. Here is the RunMario.java file:

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.Scanner;

public class RunMario {

    private MarioObstacles marioObstacles;

    public RunMario(MarioObstacles marioObstacles) {
    this.marioObstacles = marioObstacles;
    }
    public static void main(String[] arguments) {
   //        RunMario runMario1 = new    RunMario(MarioObstacles.getInstance());
        System.out.println("first line of main");

        ApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml");
        System.out.println("just out of context");

        RunMario obj = (RunMario) context.getBean("obstacle1");
        obj.start();
    }

    public void start() {
        System.out.println("first line of start");
        BuildOstacles pyramid = marioObstacles.pyramid();
        pyramid.setHeight(runMario());
        pyramid.buildPyramid();
        System.out.println(pyramid);
        System.out.println("exiting start");
    }

    public static int runMario() {
        System.out.println("entering runMario");
        int height;
        do {
            Scanner scan = new Scanner(System.in);
            System.out.println("Please enter a whole number between 1 and 10");
            height = scan.nextInt();
        } while (height < 1 || height > 10);
        return height;
    }
}

I have spent 2 days searching for the answer. I cannot seem to figure it out.

Any suggestions?

Android serialization issue

I am trying to write object data to a file (how it's done in a standard java program) in an android program and am running in to some issues. Here's the code:

public static final String storeDir = "Adata"; 
public static final String storeFile = "albums";


public static void write(ArrayList<Album> albums) throws IOException {
    ObjectOutputStream oos = new ObjectOutputStream( new FileOutputStream(storeDir + File.separator + storeFile));
    oos.writeObject(albums);
}

public static ArrayList<Album> read() throws IOException, ClassNotFoundException{
    ObjectInputStream ois = new ObjectInputStream( new FileInputStream(storeDir + File.separator + storeFile));

    return (ArrayList<Album>)ois.readObject();
}

At startup the app crashes and says, "java.io.FileNotFoundException: Adata/albums (No such file or directory)

The folder Adata folder is in the project folder at the same point as the src. Any help is appreciated. Thanks.

Any way to change background color of custom shape on click

I have a custom shape for my ListView background. But now it will not change color on click. Is there any way of doing this? Here is my xml for the ListView:

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"

    android:textSize="25sp"
    android:textColor="#ff8d8d8d"/>
<TextView
    android:id="@+id/textView2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@id/textView"
    android:layout_alignParentLeft="true"
    android:textColor="#ff8d8d8d"
    android:textSize="25sp" />
<TextView
    android:id="@+id/textView3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@id/textView1"
    android:layout_alignParentRight="true"
    android:textColor="#ff8d8d8d"
    android:textSize="25sp" />

Here is the CustomShape:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://ift.tt/nIICcg"
android:shape="rectangle">

<gradient android:startColor="#ffffff"
    android:endColor="#ffd6d4d6"
    android:angle="270"
/>
<corners android:bottomRightRadius="10dp" android:bottomLeftRadius="10dp"
    android:topLeftRadius="10dp" android:topRightRadius="10dp"/>

Java: Stopping application - what happens with objects in memory

I am wondering.. I have an application started on eclipse, simple Java application that is creating some objects in memmory that are leaking... For example I create a class with static hashmap storing strong references to objects. I am nearly running out of memory and I stop application clicking stop in Eclipse or kill -9 procId. I started that application with some jvm parameters like xms, xmx, maxpermsize. What happens with those created objects in JVM Heap / permgen? As long as the application was alive I had a method where I put strong references to static hashmap keys and it was not GC-ed (I checked it in VisualVM->VisualGC). Now I killed this application, what happens with these obects are they GC-ed immidiatelly or not GC-ed and the Heap allocated by my application is suddenly released without checking strong/weak references? How this mechanism is called?

Is there any condition where Bigdecimal with MathContext.DECIMAL32 does not provides correct result?

System.out.println("Result="+new BigDecimal(((63.19* 15) + (63.37* 5))).divide(new BigDecimal(15 + 5), MathContext.DECIMAL64).doubleValue());

Result=63.23499999999999

But with MathContext.DECIMAL32 we are getting correct result, see below:

System.out.println("Result="+new BigDecimal(((63.19* 15) + (63.37* 5))).divide(new BigDecimal(15 + 5), MathContext.DECIMAL32).doubleValue());

Result=63.235

JSON deserialisation using Jackson: No suitable constructor found for type - providing default constructor or annotate constructor is imposible

I used Jackson ObjectMapper to serialise object hierarchy to json String. After that I wanted to deserialize the object back. I got exception as below.

The important thing is that APINewDealArrangementImpl class hierarchy is out of the scope of my changes - it is part of external library. In this case I'm not able to implement default constructor nor use @JsonCreator annotion.

How can I avoid "No suitable constructor found" Exception? Is it possible to conquer this problem using some custom TypeResolverBuilder implementation or other functionalities in Jackson API? Thanks for help.

org.codehaus.jackson.map.JsonMappingException: No suitable constructor found for type [simple type, class com.tzero.api.transactions.TransactionState]: can not instantiate from JSON object (need to add/enable type information?)
 at [Source: java.io.StringReader@57ac3379; line: 4, column: 5] (through reference chain: com.tzero.api.java.transactions.APINewDealArrangementImpl["state"])
    at org.codehaus.jackson.map.JsonMappingException.from(JsonMappingException.java:163)
    at org.codehaus.jackson.map.deser.BeanDeserializer.deserializeFromObjectUsingNonDefault(BeanDeserializer.java:746)
    at org.codehaus.jackson.map.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:683)
    at org.codehaus.jackson.map.deser.BeanDeserializer.deserialize(BeanDeserializer.java:580)
    at org.codehaus.jackson.map.deser.SettableBeanProperty.deserialize(SettableBeanProperty.java:299)
    at org.codehaus.jackson.map.deser.SettableBeanProperty$MethodProperty.deserializeAndSet(SettableBeanProperty.java:414)
    at org.codehaus.jackson.map.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:697)
    at org.codehaus.jackson.map.deser.BeanDeserializer.deserialize(BeanDeserializer.java:580)
    at org.codehaus.jackson.map.ObjectMapper._readMapAndClose(ObjectMapper.java:2732)
    at org.codehaus.jackson.map.ObjectMapper.readValue(ObjectMapper.java:1863)

Invoke Java class pulled from Sigar library into web page

This small java class is running perfect and retrieving the expected data which is the number of core in processor, the problem is I'm looking for a way to display this output into web format such as JSP or HTML I have tried to invoke into JSP and JSTL but is fail and showing Sigar error:

java.lang.UnsatisfiedLinkError: org.hyperic.sigar.Sigar.getCpuInfoList()[Lorg/hyperic/sigar/CpuInfo;

My JSP file:

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <h1>Memory Data</h1>
        <%@ page import="mydata.test.*"%>
        <%
      Sigar sigar = new Sigar();
      test mytest = new test();

      out.println(sigar.getCpuInfoList());

%>
    </body>
</html>

My test.java class:

public class test {

    public test() {
        Sigar sigar = new Sigar();
        String output = " ";
        CpuInfo[] cpuInfoList = null;
        try {
            cpuInfoList = sigar.getCpuInfoList();
        } catch (SigarException e) {
            return;
        }

        for (CpuInfo info : cpuInfoList) {
            output += "Core: " + info.getCoresPerSocket()+"\n";
        }
        System.out.println(output);
    }

    public static void main(String[] args) {
        test main = new test();
    }
}

Javassist - CannotCompileException: constructor/method declaration not found

I've got the following class which i want to use in my generated code with Javassist.

public class SomeClass {
    private String someString;
    private Object someValue;

    public SomeClass() {}

    public SomeClass(String someString, Object someValue) {
        this.someString = someString;
        this.someValue = someValue;
    }

    public void setSomeValue(Object someValue) {
        this.someValue = someValue;
    }

In Javassist i analyse some classes and their fields and then try to instatiate my SomeClass-class. But i get the following error for each field which has another type then java.lang.Object.

javassist.CannotCompileException: [source error] setSomeValue(int) not found in com.test.SomeClass

and

javassist.CannotCompileException: [source error] setSomeValue(double) not found in com.test.SomeClass

and so on. The same happens when i try to use the constructor.

Why this doesn't work?

By the way, Javassist is used in conjunction with Android.

Android gradle modules with the same name

I am working on an Android project that uses the following dependency:

    <dependency>
        <groupId>org.glassfish.jersey.core</groupId>
        <artifactId>jersey-client</artifactId>
        <version>2.17</version>
    </dependency>

However this dependency has 2 definitions of the module javax/inject as shown here in the gradle dependency tree:

 +--- org.glassfish.jersey.core:jersey-client:2.17
 |    +--- org.glassfish.jersey.core:jersey-common:2.17
 |    |    +--- org.glassfish.hk2:hk2-api:2.4.0-b10
 |    |    |    +--- javax.inject:javax.inject:1
 |    |    +--- org.glassfish.hk2.external:javax.inject:2.4.0-b10

When attempting to run the Android application I get the error:

com.android.dex.DexException: Multiple dex files define L/javax/inject/Inject

I have tried excluding either of these modules but that does not work because the dependency relies on both of them to make method calls.

Are there any other solutions to resolve this conflict?

Hidden tab headers on Tabbed Activity

As a beginner of Android Studio, I have a main activity with an image button that starts Tabbed activity. I've added a new activity using

Right Click > New > Activity > Tabbed Activity

It creates activity_tabbed.xml and fragment_tabbed.xml

fragmented_tabbed.xml contgains :

<RelativeLayout xmlns:android="http://ift.tt/nIICcg"
    xmlns:tools="http://ift.tt/LrGmb4" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context="com.webraya.t0.t0.Tabbed$PlaceholderFragment">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/imageView"
        android:src="@drawable/a"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />
</RelativeLayout>

and activity_tabbed.xml contains :

<android.support.v4.view.ViewPager xmlns:android="http://ift.tt/nIICcg"
xmlns:tools="http://ift.tt/LrGmb4" android:id="@+id/pager"
android:layout_width="match_parent" android:layout_height="match_parent"
tools:context="com.webraya.t0.t0.Tabbed" />

When I run the app and touch the imagebutton and the Tabbed activity starts, the result is : enter image description here

when I swipe from right to left, it seems I have 3 tabs with the same picture. I don't know why there is no tab header, and why there are three tabs with the same content, how to create headers and change tabs contents? My theme is Theme.AppCombat.Light.DarkActionBar

Any help would be appreciated.

Java Swing JWindow application crash

If I use JDK1.8_40 or newer (Oracle or OpenJDK do the same), the following code together with a dialog resize will crash the application (tried Windows 7, x64, 64bit JDK)

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.JWindow;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Main {

public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            final JDialog dialog = new JDialog();
            dialog.add(new JPanel());
            dialog.setVisible(true);
            dialog.setBounds(100, 100, 100, 100);

            final JWindow dependentWindow = getjWindow(dialog);
            dependentWindow.setVisible(true);
            dependentWindow.setBounds(100, 100, 100, 100);
            Timer t = new Timer(300, new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    dependentWindow.setVisible(!dependentWindow.isVisible());
                }
            });
            t.start();
        }
    });
}

private static JWindow getjWindow(JDialog dialog) {
    JWindow w = new JWindow(dialog);
    JPanel panel = new JPanel();
    panel.add(new JButton("button"));
    w.add(panel);
    return w;
}
}

I haven't found other complaints about this and haven't posted a bug on oracle's website yet. A possible workaround is changing the JWindow to an undecorated JDialog but that comes with other issues for me so I wouldn't change this yet.

Did anyone else hit this problem and found a workaround?

Added the stack:

WARN 2015-05-04 15:21:21,707 - AWT-EventQueue-0, Id = 17, Priority = 6: RUNNABLE
sun.awt.windows.WWindowPeer.reshapeFrame(Native Method)
sun.awt.windows.WDialogPeer.reshape(Unknown Source)
sun.awt.windows.WComponentPeer.setBounds(Unknown Source)
sun.awt.windows.WWindowPeer.setBounds(Unknown Source)
java.awt.Component.reshapeNativePeer(Unknown Source)
java.awt.Component.reshape(Unknown Source)
java.awt.Window.reshape(Unknown Source)
java.awt.Component.setBounds(Unknown Source)
java.awt.Window.setBounds(Unknown Source)
java.awt.Component.resize(Unknown Source)
java.awt.Component.setSize(Unknown Source)
java.awt.Window.setSize(Unknown Source)

Windows problem details (shows 2 errors):

Problem signature:
Problem Event Name: BEX64
Application Name:   java.exe
Application Version:    8.0.60.13
Application Timestamp:  55404a69
Fault Module Name:  StackHash_08b3
Fault Module Version:   0.0.0.0
Fault Module Timestamp: 00000000
Exception Offset:   0000000300000002
Exception Code: c0000005
Exception Data: 0000000000000008
OS Version: 6.1.7601.2.1.0.256.48
Locale ID:  1033
Additional Information 1:   08b3
Additional Information 2:   08b36dcca93c38acb7c92ef4a729e798
Additional Information 3:   5d68
Additional Information 4:   5d682eddcc7a5d6b5452fc95535d5ac9

second one:

Problem signature:
Problem Event Name: APPCRASH
Application Name:   java.exe
Application Version:    8.0.60.13
Application Timestamp:  55404a69
Fault Module Name:  StackHash_d693
Fault Module Version:   0.0.0.0
Fault Module Timestamp: 00000000
Exception Code: c000041d
Exception Offset:   0000000300000002
OS Version: 6.1.7601.2.1.0.256.48
Locale ID:  1033
Additional Information 1:   d693
Additional Information 2:   d6933f192f50114566e03a88a59a6417
Additional Information 3:   9096
Additional Information 4:   9096dfe271c183defc2620e74bdaec28

Execute MySQL statement in the background automatically

I want to delete records from MySQL table which were not updated for longer than 3 minutes. How can I set the timer in the background to manage it without being invoked by events or methods in Java? Is that possible?

DELETE FROM bus WHERE created_at < (NOW() - INTERVAL 5 MINUTE) 

How to save audio sample data from .wav file to text file and vice versa, for resampling in android.

I have recorded and saved audio to a .wav file in android application. I want to read the sample data from .wav file (which I have done already), save that to a text file and vice versa, for resampling.

Hibernate. PSQLException: bad value for type int : admin

Well I have a desktop application with JAVA and Hibernate 4.3.1. For now I have just two entities (User and Role). I'm searching and researching for two days and nothing... =/ I need help.

User

...

@ManyToOne(fetch = FetchType.LAZY)
@Fetch(FetchMode.JOIN)
@JoinColumn(nullable = false, name = "fk_role")
private Role fk_role;

...

Role

...

@Column(name = "admin", nullable = false)
@Type(type = "org.hibernate.type.BooleanType")
private boolean admin = false;

...

I have tried instead

@Type(type = "org.hibernate.type.BooleanType")

this.

@Type(type = "org.hibernate.type.NumericBooleanType")

and

@Type(type = "org.hibernate.type.YesNoType")

and

@Type(type = "org.hibernate.type.TrueFalseType")

As shown here: http://ift.tt/1bvsxXR

And nothing. =/

I tried this too: http://ift.tt/1bvsz1F

=( In the database, the type for column admin is boolean and I use Postgres 9.3. When I run this, I got the following: --

org.hibernate.exception.DataException: could not execute query
    at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:135)
    at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:126)
    at org.hibernate.loader.Loader.doList(Loader.java:2554)
    at org.hibernate.loader.Loader.doList(Loader.java:2537)
    at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2367)
    at org.hibernate.loader.Loader.list(Loader.java:2362)
    at org.hibernate.loader.custom.CustomLoader.list(CustomLoader.java:353)
    at org.hibernate.internal.SessionImpl.listCustomQuery(SessionImpl.java:1869)
    at org.hibernate.internal.AbstractSessionImpl.list(AbstractSessionImpl.java:311)
    at org.hibernate.internal.SQLQueryImpl.list(SQLQueryImpl.java:141)
    at com.print.model.schemaPublic.gateway.UserGateway.list(UserGateway.java:61)
    at com.print.model.schemaPublic.UserBusiness.list(UserBusiness.java:22)
    at com.print.controller.MenuController.fileNovoAction(MenuController.java:22)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at com.library.core.ActionListenerDelegate.actionPerformed(ActionListenerDelegate.java:48)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018)
    at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2341)
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
    at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
    at javax.swing.AbstractButton.doClick(AbstractButton.java:376)
    at javax.swing.plaf.basic.BasicMenuItemUI.doClick(BasicMenuItemUI.java:833)
    at javax.swing.plaf.basic.BasicMenuItemUI$Handler.mouseReleased(BasicMenuItemUI.java:877)
    at java.awt.Component.processMouseEvent(Component.java:6516)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3320)
    at java.awt.Component.processEvent(Component.java:6281)
    at java.awt.Container.processEvent(Container.java:2229)
    at java.awt.Component.dispatchEventImpl(Component.java:4872)
    at java.awt.Container.dispatchEventImpl(Container.java:2287)
    at java.awt.Component.dispatchEvent(Component.java:4698)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4832)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4492)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4422)
    at java.awt.Container.dispatchEventImpl(Container.java:2273)
    at java.awt.Window.dispatchEventImpl(Window.java:2719)
    at java.awt.Component.dispatchEvent(Component.java:4698)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:735)
    at java.awt.EventQueue.access$200(EventQueue.java:103)
    at java.awt.EventQueue$3.run(EventQueue.java:694)
    at java.awt.EventQueue$3.run(EventQueue.java:692)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)
    at java.awt.EventQueue$4.run(EventQueue.java:708)
    at java.awt.EventQueue$4.run(EventQueue.java:706)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:705)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:91)

Caused by: org.postgresql.util.PSQLException: bad value for type int: admin

Thank you very much everybody.

JavaFX Error with Netbeans Standard FXML application - Nullpointer for .fxml file

When I create a new Netbeans Projekt (JavaFX FXML Application) with application class I receive a template as usual (one .fxml, one controller class and the main application). When I try to run this I get an exception:

Exception in thread "main" java.lang.RuntimeException: Exception in Application start method
    at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:403)
    at com.sun.javafx.application.LauncherImpl.access$000(LauncherImpl.java:47)
    at com.sun.javafx.application.LauncherImpl$1.run(LauncherImpl.java:115)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.NullPointerException: Location is required.
    at javafx.fxml.FXMLLoader.load(FXMLLoader.java:2825)
    at javafx.fxml.FXMLLoader.load(FXMLLoader.java:2809)
    at javafx.fxml.FXMLLoader.load(FXMLLoader.java:2795)
    at javafx.fxml.FXMLLoader.load(FXMLLoader.java:2782)
    at javafx.fxml.FXMLLoader.load(FXMLLoader.java:2771)
    at volltextsuche.Volltextsuche.start(Volltextsuche.java:25)
    [...]

This is my start() method:

@Override
public void start(Stage stage) throws Exception {
    URL url = getClass().getResource("FXMLDocument.fxml");
    System.out.println(url == null);
    Parent root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));
    Scene scene = new Scene(root);
    stage.setScene(scene);
    stage.show();
}

and somehow the URL is null. Line 25 is the Parent root = [...] part. The .fxml document has the exact same name as the Strings tell and is in the same package as the main application class. I didn't change anything, just the null check for the URL. I googled for a long time, but I couldn't find anything regarding this error.

  • JDK 8.0_45
  • Netbeans 8.0.2
  • Win 8.1 x64

results of one of the ways to declare a new object with a parent class and a subclass

I have a Java-related question.

I have a public class Parent and its subclass public class Child extends Parent.

If I were to declare a new object as

Parent p = new Child();

would p be able to use the methods of Child and Parent? Or only Parent?

Additionally, what would be the difference in declaring p as

Child p = new Child(); 

if Child extends parent already?

Need help by setting up log4j RemoteLogging

I need your help for a small java project.

My plan is to build a GUI to show log events fired by several applications using log4j. But I´m too confused by the different buzzwords for remote-logging with log4j.

Which log4j-structure should i use? SimpleSocketServer? SocketReceiver? SyslogAppender? SocketNote?

Do you have a good example where I can see how to correctly setup such a small application?

Showing data using JSP

I'm making an ordering system using Java servlet and JSP. The problem is I can't view the menu list on JSP page after passed it from a servlet. Here is my code.

Menu.java

public class Menu implements Serializable {

    private static final long serialVersionUID = -8072555192585991919L;

    private int menuId;
    private String menuName;
    private double menuPrice;

    public Menu(String menuName,double menuPrice) {
        this.setMenuName(menuName);
        this.setMenuPrice(menuPrice);
    }

    public Menu() {
        setMenuName("");
        setMenuPrice(0);
    }

    public double getMenuPrice() {
        return menuPrice;
    }

    public void setMenuPrice(double menuPrice) {
        this.menuPrice = menuPrice;
    }

    public String getMenuName() {
        return menuName;
    }

    public void setMenuName(String menuName) {
        this.menuName = menuName;
    }

    public int getMenuId() {
        return menuId;
    }

    public void setMenuId(int menuId) {
        this.menuId = menuId;
    }

}

MenuDAO.java

public List<Menu> getAllMenu() {
    List<Menu> menus = new ArrayList<>();
    try {
        Statement statement = con.createStatement();
        ResultSet rs = statement.executeQuery("select * from cafemenu");

        while(rs.next()){
            Menu menu = new Menu();
            menu.setMenuId(rs.getInt("menu_id"));
            menu.setMenuName(rs.getString("menu_name"));
            menu.setMenuPrice(rs.getDouble("menu_price"));
            menus.add(menu);
        }

    } catch(Exception e) {
        e.printStackTrace();
    }
    return menus;
}

ListMenuServlet.java

public class MenulistServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    List<Menu> listMenu = new ArrayList<>();

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        listMenu = new MenuDao().getAllMenu();
        request.setAttribute("list", listMenu);
        request.getRequestDispatcher("welcome.jsp").forward(request, response); 
    }
}

welcome.jsp

<%@ taglib prefix="c" uri="http://ift.tt/QfKAz6" %>

<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
  <title>Welcome</title>
</head>
<body>
  <table border="1" width="100%">
      <tr>
        <th>Menu ID</th>
        <th>Menu Name</th>
        <th>Menu Price</th>
      </tr>
    <c:forEach var="row" items="${list}">
      <tr>
        <td>${row.menu_id}</td>
        <td>${row.menu_name}</td>
        <td>${row.menu_price}</td>
      </tr>
    </c:forEach>
  </table>
</body>
</html>

I tried to check few times but still can't get the table to work. It only showing the header of the table, and nothing more.

Thanks for the help!

Cassandra - can't remove the nodes

I've accidently added new nodes to the test cluster. I removed the nodes afterwards but they still appear when connecting to the cluster.

The nodetool gossipinfo doesn't show them. The nodetool ring doesn't either but when connecting via the datastax Java client they do appear:

LOG4J 2015-05-06 15:44:54.796 INFO : [Cluster] - New Cassandra host /198.81.xxx.32 added LOG4J 2015-05-06 15:44:54.797 INFO : [Cluster] - New Cassandra host /198.81.xxx.31 added

How do I remove these nodes from the gossip cache/events, where do they come from?

Android scaling/transforming canvas doesn't modify clickable area

I'm having a very similar issue described here, except instead of using ScaleAnimation, I'm allowing pinch zoom/pan in my RelativeLayout.

The zoom/panning works perfectly, but regardless of how my view is panned/zoomed, the clickable area does not change along with the visual representation. Here's what my dispatchTouchEvent looks like:

@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
    if (mScaleGestureDetector != null && mGestureDetector != null) {
        mScaleGestureDetector.onTouchEvent(ev);
        mGestureDetector.onTouchEvent(ev);
    }

    final int action = ev.getAction();
    switch (action & MotionEvent.ACTION_MASK) {
        case MotionEvent.ACTION_DOWN: {
            final float x = ev.getX();
            final float y = ev.getY();

            mLastTouchX = x;
            mLastTouchY = y;
            mActivePointerId = ev.getPointerId(0);
            break;
        }

        case MotionEvent.ACTION_MOVE: {
            final int pointerIndex = ev.findPointerIndex(mActivePointerId);
            final float x = ev.getX(pointerIndex);
            final float y = ev.getY(pointerIndex);

            // Only move if the ScaleGestureDetector isn't processing a gesture.
            if (!mScaleGestureDetector.isInProgress() && mScaleFactor > 1f) {
                final float dx = x - mLastTouchX;
                final float dy = y - mLastTouchY;

                float newPosX = mPosX + dx;
                float newPosY = mPosY + dy;
                if (isCoordinateInBound(newPosX, mScreenSize.x))
                    mPosX = newPosX;
                if (isCoordinateInBound(newPosY, mScreenSize.y))
                    mPosY = newPosY;

                invalidate();
            }

            mLastTouchX = x;
            mLastTouchY = y;

            break;
        }

        case MotionEvent.ACTION_UP: {
            mActivePointerId = INVALID_POINTER_ID;
            break;
        }

        case MotionEvent.ACTION_CANCEL: {
            mActivePointerId = INVALID_POINTER_ID;
            break;
        }

        case MotionEvent.ACTION_POINTER_UP: {
            final int pointerIndex = (ev.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK)
                    >> MotionEvent.ACTION_POINTER_INDEX_SHIFT;
            final int pointerId = ev.getPointerId(pointerIndex);
            if (pointerId == mActivePointerId) {
                final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
                mLastTouchX = ev.getX(newPointerIndex);
                mLastTouchY = ev.getY(newPointerIndex);
                mActivePointerId = ev.getPointerId(newPointerIndex);
            }
            break;
        }
    }

    return super.dispatchTouchEvent(ev);
}

and my dispatchDraw:

protected void dispatchDraw(Canvas canvas) {
    canvas.save(Canvas.MATRIX_SAVE_FLAG);
    canvas.translate(mPosX, mPosY);

    canvas.scale(mScaleFactor, mScaleFactor);
    super.dispatchDraw(canvas);
    canvas.restore();
}

How do you modify the clickable area accordingly to modified scale/transformation of canvas?

For loops and Arrays - Java Swing

I am new to SO, but I am really lost with this... I have declared and instantiated an array of 10 JButtons in Java Swing. I have also done the same for an array of my 10 custom object (Crime). What I want to do is when each button is clicked, I want a JOptionPane to display the crime details Here is my code:

for(int i=0; i<buttons.length; i++){
    buttons[i].addActionListener(new ActionListener(){
         public void actionPerformed(ActionEvent e){
             JOptionPane.showMessageDialog(null, crimes[i].getDescription(), "Crime", JOptionPane.INFORMATION_MESSAGE, null); 

I keep getting an array out of bounds exception which makes no sense since there are the same number of elements in each array?

"Variable not initalised" error

I think I found something weird.. Or it could just be something that I don't understand. I get this error when I tried to add a ActionListener to my popupRequest variable as shown in the code snippet.

error: variable popupRequest might not have been initialized
            popupRequest.addActionListener(new ActionListener() {
1 error

So meaning to say my popupRequest isn't initialised and that is probably why the error is thrown. But the thing is I did initialise that variable.

Code Snippet

JPopupMenu popup = new JPopupMenu();
JMenuItem popupTitle,popupHostJoin,popupRequest;
if (SwingUtilities.isRightMouseButton(evt)) {
        JL_CurrentUsers.setSelectedIndex(JL_CurrentUsers.locationToIndex(evt.getPoint()));
        popup.add(popupTitle = new JMenuItem("Private Message"));
        popup.addSeparator();
        if (nickname.equals(JL_CurrentUsers.getSelectedValue())) 
            popup.add(popupHostJoin = new JMenuItem("Host..."));
        else {
            popup.add(popupRequest = new JMenuItem("Request..."));//I initialise it here
            popup.add(popupHostJoin = new JMenuItem("Join..."));
        }

        popupHostJoin.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                new PvtMessageGUI(fHost,fPort,nickname).setVisible(true);
            }
        });
        //this is the line that gives me that error 
        popupRequest.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                client.sendMessage(new ChatMessage(ChatMessage.REQUEST,nickname+"->"+JL_CurrentUsers.getSelectedValue()));
            }
        });
        popup.show(JL_CurrentUsers,evt.getX(),evt.getY());
    }

I can work around it by initialising my popupRequest when i first declare the variable.

JMenuItem popupTitle,popupHostJoin,popupRequest=new JMenuItem("Request"...);

What I wanna know is.. What is the difference between initialising my popupRequest when I declared it at the beginning, and initialising it inside my if-else statement? And I don't see why the program didn't detect the initialised popupRequest but it did for the initialised popupHostJoin variable when I added the ActionListener to it.

P.S. I hope my post isn't too confusing.

ANT property environment="env" unable to retrieve it in JAVA but works fine if run as ant command

I've a build file which will be called from java. Please find the build.xml below.

<property environment="env"/>
  <echo message="${env.PATH}"/>
  <echo message="${env.SSH_CONNECTION}"/>
  <echo message="${env.JAVA_HOME}"/>
  <echo message="${env.HOME}"/>
  <echo message="${env.IS_HOME}"/>
  <echo message="${basedir}"/>

Unable to fetch the environment variables if its run through java class. But the same works fine if run as ant command like "ant". Please help

iF run as JAVA then error is

--- MESSAGE LOGGED
Property ${env.JAVA_HOME} has not been set
--- MESSAGE LOGGED
     [echo] ${env.JAVA_HOME}

But i could see that the environment variables are set fine. If i echo the variables command line , im able to see the value.

Given the following JSON file display a list of messages grouped by user

I'm able to read a JSON file containing a list of messages and their corresponding authors. The structure of a single message is the following:

JSON

{  
   "created_at":"Thu Apr 30 10:47:49 +0000 2015",
   "id":593728455901990912,
   "user":{  
      "id":12,
      "name":"GiGi",
      "user_date":"Thu May 17 10:47:49 +0000 2010",
   },
}

The Author and Message classes (POJOs) contain the fields that we want to parse and a function toString() that display the fields in a string.

Author

public class Author {

    @SerializedName("id")
    private static long id;

    @SerializedName("created_at")
    private static String user_date;

    private static String name;

    public  String toString() {
        return name + "\n" + id + "\n" + user_date;         
    }

}

Message

public class Message {

    @SerializedName("user")
    Author author;   

    @SerializedName("created_at")
    String date;

    long id;

    public String toString() {
        return id + "\n" + date;        
    }

}

Author is a member class of the Message class and i need to display the messages grouped by user but i don't seem to find an elegant way of doing it.

Any suggestions?

Use Spring together with Spark

I'm developing a Spark Application and I'm used to Spring as a Dependency Injection Framework. Now I'm stuck with the problem, that the processing part uses the @Autowired functionality of Spring, but it is serialized and deserialized by Spark.

So the following code gets me into trouble:

Processor processor = ...; // This is a Spring constructed object
                           // and makes all the trouble
JavaRDD<Txn> rdd = ...; // some data for Spark
rdd.foreachPartition(processor);

The Processor looks like that:

public class Processor implements VoidFunction<Iterator<Txn>>, Serializeable {
    private static final long serialVersionUID = 1L;

    @Autowired // This will not work if the object is deserialized
    private transient DatabaseConnection db;

    @Override
    public void call(Iterator<Txn> txns) {
        ... // do some fance stuff
        db.store(txns);
    }
}

So my question is: Is it even possible to use something like Spring in combination with Spark? If not, what is the most elegant way to do something like that? Any help is appreciated!

Package-by-layer versus package-by-feature

I know this has several associated posts, but I have some specific questions which I am hoping I can get help with. Sorry if they are very basic..

Here is a sample problem - very simplified, but you get the picture - I have several objects, which have some common function e.g. departments in a pharmaceutical company - neurology, oncology, infection etc. They all need to parse patient document files, and upload data to the database. Of course the nature of the data is slightly different for each department. If I used package-by-feature, I would have

com.company.neurology
      Neurology.java
      NeurologyDocument.java
      NeurologyDAO.java

com.company.infection
      Infection.java
      InfectionDocument.java
      InfectionDAO.java

etc. The problem is that I need an abstract class that the Document classes need to extend e.g.

AbstractDocument.java
public class AbstractDocument
{
      public void validateDocument(){...}
      public void readDocumentHeader(){...}
      public void readDocumentFooter(){...}
       ...
}

Some data access files e.g.

DBConnection.java
    public class DBConnection
    {
        public void makeConnectionToDB() {... }
        public void createCache() {... }
        public void closeConnectionToDB() {... }
    }

some error classes

ParseError.java, PatientNotFoundException etc.

If packages are by feature, where do these common classes/interfaces go?

Cant validate Login on Android app using an api request

i'm trying to create a login form that connects to an API and authorizes the username and password but whenever i press the onClickListener which is my LogIn button the app crashes. The username and password is hardcoded in my code.

Code:

public class LoginActivity extends ActionBarActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(layout.activity_login);

    Button buttonLogin =  (Button)findViewById(id.buttonLogin);
    EditText uEmail = (EditText) findViewById(id.emailField);
    EditText uPassword = (EditText) findViewById(id.passwordField);

    buttonLogin.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            final OkHttpClient client = new OkHttpClient();

            client.setAuthenticator(new Authenticator() {
                @Override
                public Request authenticate(Proxy proxy, Response response) throws IOException {
                    String credential = Credentials.basic("username", "password");
                    return response.request().newBuilder()
                            .header("Authorization", credential)
                            .build();
                }

                @Override
                public Request authenticateProxy(Proxy proxy, Response response) throws IOException {
                    return null;
                }
            });

            Request request = new Request.Builder().url("MyUrlThatIdontWannaShow").build();

            Call call = client.newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Request request, IOException e) {
                    Context context = getApplicationContext();
                    CharSequence text = "Error";
                    int duration = Toast.LENGTH_SHORT;

                    Toast toast = Toast.makeText(context, text, duration);
                    toast.show();
                }

                @Override
                public void onResponse(Response response) throws IOException {
                    Context context = getApplicationContext();
                    CharSequence text = "Hello toast!";
                    int duration = Toast.LENGTH_SHORT;

                    Toast toast = Toast.makeText(context, text, duration);
                    toast.show();
                }
            });
        }

    });

}

}

The error i get:

C:\Users\Dan\AndroidStudioProjects\LogsterAndroid\app\src\main\java\com\example\danial\logsterandroid\LoginActivity.java:23: error: cannot find symbol uEmail = (EditText)findViewById(R.id.emailField); ^ symbol: variable uEmail location: class LoginActivity C:\Users\Dan\AndroidStudioProjects\LogsterAndroid\app\src\main\java\com\example\danial\logsterandroid\LoginActivity.java:24: error: cannot find symbol uPassword = (EditText)findViewById(R.id.passwordField); ^ symbol: variable uPassword location: class LoginActivity 2 errors

FAILED

FAILURE: Build failed with an exception.

  • What went wrong: Execution failed for task ':app:compileDebugJava'.

    Compilation failed; see the compiler error output for details.

  • Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

Thanks in advance!

Publisher-Subscriber setup with WatchService

I am trying to setup a 2 way publisher-subscriber using the WatchService in NIO.

I'm not terribly experienced with threads, so if I'm not making any sense feel free to call me out on it!

This is only a sample to figure out how the library works, but the production code is going to listen for a change in an input file, and when the file changes it will do some calculations and then write to an output file. This output file will be read by another program, some calculations will be run on it. The input file will then be written to and the cycle continues.

For this test though, I am making 2 threads with watchers, the first thread listens on first.txt and writes to second.txt, and the second thread waits on second.txt and writes to first.txt. All that I am doing is incrementing a count variable and writing to each thread's output file. Both of the threads have blocking calls and filters on what files they actually care about, so I figured the behavior would look like

Both threads are waiting on take() call. Change first.txt to start the process This triggers the first thread to change second.txt Which then triggers the second thread to change first.txt and so on.

Or so I hoped. The end result is that the threads get way out of sync and when I do this for count up to 1000, one thread is usually behind by more than 50 points.

Here is the code for the watcher

Watcher(Path input, Path output) throws IOException {
    this.watcher = FileSystems.getDefault().newWatchService();
    this.input = input;
    this.output = output;
    dir = input.getParent();
    dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
}

void watchAndRespond() throws IOException, InterruptedException {

    while (count < 1000) {

        WatchKey key = watcher.take();

        for (WatchEvent<?> event: key.pollEvents()) {
            if (! event.context().equals(input.getFileName())) {
                continue;
            }

            WatchEvent.Kind kind = event.kind();
            if (kind == OVERFLOW) {
                continue;
            }

            count++;

            try (BufferedWriter out = new BufferedWriter(new FileWriter(output.toFile()))) {
                out.write(count + "");
            }
        }
        key.reset();
    }
}

I don't want to have to read the file to decide whether or not the file has changed, because these files in production could potentially be large.

I feel like maybe it is too complicated and I'm trying to deal with a scraped knee with amputation. Am I using this library incorrectly? Am I using the wrong tool for this job, and if so are there any other file listening libraries that I can use so I don't have to do polling for last edited?

EDIT: Oops, here is the test I wrote that sets up the two threads

@Test
public void when_two_watchers_run_together_they_end_up_with_same_number_of_evaluation() throws InterruptedException, IOException {
    //setup
    Path input = environment.loadResourceAt("input.txt").asPath();
    Path output = environment.loadResourceAt("output.txt").asPath();

    if (Files.exists(input)) {
        Files.delete(input);
    }
    if (Files.exists(output)) {
        Files.delete(output);
    }

    Thread thread1 = makeThread(input, output, "watching input");
    Thread thread2 = makeThread(output, input, "watching output");

    //act
    thread1.start();
    thread2.start();

    Thread.sleep(50);

    BufferedWriter out = new BufferedWriter(new FileWriter(input.toFile()));
    out.write(0 + "");
    out.close();

    thread1.join();
    thread2.join();

    int inputResult = Integer.parseInt(Files.readAllLines(input).get(0));
    int outputResult = Integer.parseInt(Files.readAllLines(output).get(0));
    //assert
    assertThat(inputResult).describedAs("Expected is output file, Actual is input file").isEqualTo(outputResult);
}

public Thread makeThread(Path input, Path output, String threadName) {
    return new Thread(() ->
    {
        try {
            new Watcher(input, output).watchAndRespond();
        }
        catch (IOException | InterruptedException e) {
            fail();
        }

    }, threadName);
}

How to add SVG image to PDF built with HTML and Flying Saucer library (and Batik)?

Im working on generation of PDFs with XHTML using the flying saucer library (old but open source). I got that working but I also want to add SVG images. Ive started working on integrating batik to try and get it to work but I'm running into issues. I cannot seem to include/append my SVG image into the PDF. The XHTML still renders, but it doesnt seem to show the SVG. I've gotten SVG to render on separate PDFs but never together with the flying saucer results. I've added the usual ReplacedElementFactory (which works with regular images as well but havent included that code). The only relevant method (that does get called and everything) is the following:

    public ReplacedElement createReplacedElement(LayoutContext LayoutContext, BlockBox blockBox, UserAgentCallback userAgentCallback, int cssWidth, int cssHeight) {
    Element element = blockBox.getElement();
    if (element == null) {
        return null;
    }
    String nodeName = element.getNodeName();
    String className = element.getAttribute("class");
    if ("svg".equals(nodeName)) {
        if (element.hasAttribute("src")){
            Document svgImage = null;
            try {
                String parser = XMLResourceDescriptor.getXMLParserClassName();
                SAXSVGDocumentFactory f = new SAXSVGDocumentFactory(parser);
                svgImage = f.createDocument(element.getAttribute("src")+".svg");
            } catch (IOException ex) {
                System.out.println(element.getAttribute("src")+".svg");
            }

            Element svgElement = svgImage.getDocumentElement();
            Document htmlDoc = element.getOwnerDocument();
            htmlDoc.importNode(svgElement, true);
            element.appendChild(svgElement);
            return new SVGReplacedElement(svgImage, cssWidth, cssHeight);
        }
    }
}

So the svgElement gets loaded and seems to be the correct image. htmlDoc is the original xhtml Document that does get rendered normaly. I try to import the svgElement into the regular xhtml dom and append it (as many examples also do, but it then gives an error:

Exception in thread "main" org.w3c.dom.DOMException: WRONG_DOCUMENT_ERR: A node is used in a different document than the one that created it.
at org.apache.xerces.dom.ParentNode.internalInsertBefore(Unknown Source)
at org.apache.xerces.dom.ParentNode.insertBefore(Unknown Source)
at org.apache.xerces.dom.NodeImpl.appendChild(Unknown Source)
at pdf.printing.MediaReplacedElementFactory.createReplacedElement(MediaReplacedElementFactory.java:73)
at org.xhtmlrenderer.render.BlockBox.calcDimensions(BlockBox.java:674)
at org.xhtmlrenderer.render.BlockBox.calcDimensions(BlockBox.java:628)
at org.xhtmlrenderer.render.BlockBox.layout(BlockBox.java:763)
at org.xhtmlrenderer.render.BlockBox.layout(BlockBox.java:732)
at org.xhtmlrenderer.layout.Layer.layoutAbsoluteChild(Layer.java:714)
at org.xhtmlrenderer.layout.Layer.layoutAbsoluteChildren(Layer.java:687)
at org.xhtmlrenderer.layout.Layer.finish(Layer.java:673)
at org.xhtmlrenderer.layout.LayoutContext.popLayer(LayoutContext.java:231)
at org.xhtmlrenderer.render.BlockBox.layout(BlockBox.java:844)
at org.xhtmlrenderer.render.BlockBox.layout(BlockBox.java:732)
at org.xhtmlrenderer.layout.BlockBoxing.layoutBlockChild0(BlockBoxing.java:293)
at org.xhtmlrenderer.layout.BlockBoxing.layoutBlockChild(BlockBoxing.java:271)
at org.xhtmlrenderer.layout.BlockBoxing.layoutContent(BlockBoxing.java:89)
at org.xhtmlrenderer.render.BlockBox.layoutChildren(BlockBox.java:922)
at org.xhtmlrenderer.render.BlockBox.layout(BlockBox.java:802)
at org.xhtmlrenderer.render.BlockBox.layout(BlockBox.java:732)
at org.xhtmlrenderer.layout.BlockBoxing.layoutBlockChild0(BlockBoxing.java:293)
at org.xhtmlrenderer.layout.BlockBoxing.layoutBlockChild(BlockBoxing.java:271)
at org.xhtmlrenderer.layout.BlockBoxing.layoutContent(BlockBoxing.java:89)
at org.xhtmlrenderer.render.BlockBox.layoutChildren(BlockBox.java:922)
at org.xhtmlrenderer.render.BlockBox.layout(BlockBox.java:802)
at org.xhtmlrenderer.render.BlockBox.layout(BlockBox.java:732)
at org.xhtmlrenderer.layout.BlockBoxing.layoutBlockChild0(BlockBoxing.java:293)
at org.xhtmlrenderer.layout.BlockBoxing.layoutBlockChild(BlockBoxing.java:271)
at org.xhtmlrenderer.layout.BlockBoxing.layoutContent(BlockBoxing.java:89)
at org.xhtmlrenderer.render.BlockBox.layoutChildren(BlockBox.java:922)
at org.xhtmlrenderer.render.BlockBox.layout(BlockBox.java:802)
at org.xhtmlrenderer.render.BlockBox.layout(BlockBox.java:732)
at org.xhtmlrenderer.pdf.ITextRenderer.layout(ITextRenderer.java:209)
at pdf.printing.Printer.print(Printer.java:206)

Afterwards Ill try to print it with:

@Override
public void paint(RenderingContext renderingContext, ITextOutputDevice outputDevice, 
        BlockBox blockBox) {

    UserAgent userAgent = new UserAgentAdapter();
    DocumentLoader loader = new DocumentLoader(userAgent);
    BridgeContext ctx = new BridgeContext(userAgent, loader);
    ctx.setDynamicState(BridgeContext.DYNAMIC);
    GVTBuilder builder = new GVTBuilder();

    blockBox.paintDebugOutline(renderingContext);

    PdfContentByte cb = outputDevice.getWriter().getDirectContent();

    float width = cssWidth / outputDevice.getDotsPerPoint();
    float height = cssHeight / outputDevice.getDotsPerPoint();

    PdfTemplate map = cb.createTemplate(width, height);

    Graphics2D g2d = map.createGraphics(width, height);

    GraphicsNode mapGraphics = builder.build(ctx, svg);
    mapGraphics.paint(g2d);
    g2d.dispose();

    PageBox page = renderingContext.getPage();
    float x = blockBox.getAbsX() + page.getMarginBorderPadding(renderingContext, CalculatedStyle.LEFT);
    float y = (page.getBottom() - (blockBox.getAbsY() + cssHeight)) + page.getMarginBorderPadding(
            renderingContext, CalculatedStyle.BOTTOM);

    cb.addTemplate(map, x, y);
}

Interesting: the blockbox.paintDebugOutline does show the outline. All of this is either textbook or a combination of textbook things. I've made sure that the css has a width height display:block etc defined for this. It is embedded in the html as <img class="icon" src="something.svg" alt=""> Im using FlyingSaucer jar and batik 1.8 and Im stuck :(

Alternatively Ive tried:

 @Override
public ReplacedElement createReplacedElement(LayoutContext layoutContext, BlockBox blockBox, UserAgentCallback userAgentCallback, int cssWidth, int cssHeight) {
    Element element = blockBox.getElement();
    if (element == null) {
        return null;
    }
    String nodeName = element.getNodeName();
    String className = element.getAttribute("class");
    if ("svg".equals(nodeName)) {
        if (element.hasAttribute("src")){
DocumentBuilderFactory documentBuilderFactory =     DocumentBuilderFactory.newInstance();
            DocumentBuilder documentBuilder;

            try {
                documentBuilder = documentBuilderFactory.newDocumentBuilder();
            } catch (ParserConfigurationException e) {
                throw new RuntimeException(e);
            }
            Document svgImage = documentBuilder.newDocument();
            element.getOwnerDocument().importNode(element, true);
            return new SVGReplacedElement(svgImage, cssWidth, cssHeight);

Which resulted in:

Exception in thread "main" java.lang.ClassCastException: org.apache.xerces.dom.DocumentImpl cannot be cast to org.apache.batik.anim.dom.SVGOMDocument
at org.apache.batik.bridge.BridgeContext.setDocument(Unknown Source)
at org.apache.batik.bridge.GVTBuilder.build(Unknown Source)
at pdf.printing.SVGReplacedElement.paint(SVGReplacedElement.java:121)
at org.xhtmlrenderer.pdf.ITextOutputDevice.paintReplacedElement(ITextOutputDevice.java:183)
at org.xhtmlrenderer.layout.Layer.paintReplacedElement(Layer.java:540)
at org.xhtmlrenderer.layout.Layer.paint(Layer.java:306)
at org.xhtmlrenderer.layout.Layer.paintLayers(Layer.java:165)
at org.xhtmlrenderer.layout.Layer.paint(Layer.java:337)
at org.xhtmlrenderer.pdf.ITextRenderer.paintPage(ITextRenderer.java:384)
at org.xhtmlrenderer.pdf.ITextRenderer.writePDF(ITextRenderer.java:348)
at org.xhtmlrenderer.pdf.ITextRenderer.createPDF(ITextRenderer.java:315)
at org.xhtmlrenderer.pdf.ITextRenderer.createPDF(ITextRenderer.java:246)
at pdf.printing.Printer.print(Printer.java:207)

Thanks a lot for your attention and feedback (and possibly answers)