Affichage des articles dont le libellé est Active questions tagged java - Stack Overflow. Afficher tous les articles
Affichage des articles dont le libellé est Active questions tagged java - Stack Overflow. Afficher tous les articles

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?