how to determine if Java heap is using compressed pointers and whether or not resides at address 0 in memory?

I am trying to follow up on some tips in this blog https://www.elastic.co/blog/a-heap-of-trouble#ref5 which discusses the benefits of sizing one’s Java heap so that (a) compressed pointers can be used (for heaps under 32GB) and (b) so that the heap resides at address 0 in memory. The article details how compressed pointers allow more efficient use of heap space, and explains that when the heap lives at address zero this reduces the amount of arithmetic necessary to resolve pointer addresses. Finally, the article says that if I use JVM options -XX:+UnlockDiagnosticVMOptions -XX:+PrintCompressedOopsMode I will see log output either like this:

heap address: 0x000000011be00000, size: 27648 MB, zero based Compressed Oops

which indicates zero-based compressed oops are enabled, or output like this

heap address: 0x0000000118400000, size: 28672 MB, Compressed Oops with base: 0x00000001183ff000

which indicates that the heap begins at an address other than zero, therefore requiring the aforementioned increase amount of arithmetic processing.

However, when I tried those options and grep’d through my application’s (Elastic Search’s) log directory I could find no such messages. If anyone could advise me on how i can force details of zero-based (or not zero based) compressed pointers to be logged I’d be very grateulful.

Library Book Issuance Database

I have to develop a database program that allows me to

  • Track student and teacher names with ability to enter/view/edit names
  • Track the issuance of books for a student or teacher
  • Manage different limits for the number of books that can be issued to a student or teacher
  • Manage the number of days that students and teachers can check out any book
  • Give each book a different ID.
  • Generate/Print weekly reports to show books issued to whom and number of days leading to the due date/return.
  • Generate/Print weekly reports of detail of fines(when a book is not returned on time)

I have multiple questions.

Do i have to use a database program like MySQL and connect it, or am I able to just input all the books and student/teacher names on an IDE like Blue J?

How would I necessarily start this off? I’ve looked at other posts on here similar to this but they already have code they’ve done and I’m stumped on how to begin this.

I’m not looking to do anything fancy at the moment, I’m just trying to make sure all these main points get done. Any help is appreciated!

How to set value to for a textarea, and get it with struts2 actions?

I am new to Struts2 web development. I’m trying to create a form where user can input the current status of an order.

In the form,

when user selects “Order Delivered”, the textarea will shows “Order delivered”;

when user selects “Order Canceled”, the textarea will shows “Order canceled”;

when user selects “Order Canceled”, the textarea wil be unlocked and user can input something in it.

My HTML and Javascript codes are as below:

function setCompleteReason(reason){
		element = document.getElementById("complete_resaon");
		switch(reason){
			case "delivered":
				element.disabled = true;
				element.value = "Order Delivered";
				break;
			case "canceled":
				element.disabled = true;
				element.value = "Order Canceled";
				break;
			case "others":
				element.disabled = false;
				element.value = "";
				break;
			default:
				element.disabled = true;
				element.value = "";
		}
	}
  
  
 function completeOrderBtn() {
		element = document.getElementById("complete_resaon");

		if( element.value.length == 0){
			alert("Please input something!");
			return false;
		}
		$('#orderForm').attr('action','ordercomplete.action');
    	$("#orderForm").submit();
	}
<select class="form-control" onchange="setCompleteReason(this.value)" id="selectReason">
							<option value=""></option>
							<option value="delivered">Order Delivered</option>
							<option value="canceled">Order Canceled</option>
							<option value="others">Other(Please Input)</option>
</select>

<textarea class="form-control" name="ordMVo.complete_reason" id="complete_resaon" cols="10" rows="5" maxlength="100" resize="false" disabled="true"></textarea>


<button type="button" class="btn btn-primary btn-dhl" data-dismiss="modal" onclick="completeOrderBtn(); return false;">Complete</button>

If users select “others” and input values by themselves. The Struts2 could get the value of the textarea via ordMVo.complete_reason in my Java actions without any problem.

However, if users selects “Order Delivered” or “Order Canceled” and let the Javascript to create value to the textarea, my Java actions only get NULL value.

Is there any special way to set a value to the text area and let Struts2 Java actions to get it ?

How to include an incomplete jar file (a jar file that some of classes it needs are missing)?

I am writing a framework in java. This framework relies on a class Class1 that will be written by the client of the framework. I want to give the jar file of my framework to the client. I want the client to write Class1, include my jar file, and compile the project. But I get error: XXX cannot be resolved to a variable

If instead of including jar file of the framework, include its project to the client project in eclipse, it works, but jar file does not work. I want to finally give my client the jar file.

Is there any way that I can solve it. If part of my question is not clear ask me to explain more.

Update: We can also think of this problem as this: How to divide a project into two projects. Create a jar file of first part and add to the second part. While first part also needs the second part?

Update: Consider the following example:

enter image description here

ClassA.java:

package part1;

public class ClassA {
    public void print(){
        ClassB b = new ClassB(); 
        b.print();
    }
}

ClassB.java:

package part2;

public class ClassB {
    public void print(){
        System.out.println("Hello from ClassB");
    }
}

MainClass.java:

package part2;

import part1.ClassA;

public class MainClass {

    public static void main(String[] args) {
        ClassA a = new ClassA();
        a.print();

    }

}

Note that ClassA will compile with error as it does not have ClassB. I will go ahead and create jar file even though we have compile error.
Also assume that we cannot change ClassB, so we cannot use interface etc. I wish use interface (or abstract class), but since I cannot change the code of ClassB I cannot.

Thanks.

error while integrating spring with hibernate

I’m trying to integrate spring with hibernate but i get this error:

[2017-10-06 05:26:14,475] Artifact spring-mvc-hibernate-example:war: java.io.IOException: com.sun.enterprise.admin.remote.RemoteFailureException: Error occurred during deployment: Exception while loading the app : java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name ‘userDaoImp’: Unsatisfied dependency expressed through field ‘sessionFactory’; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘getSessionFactory’ defined in com.boraji.tutorial.spring.config.AppConfig: Invocation of init method failed; nested exception is org.hibernate.exception.GenericJDBCException: Unable to open JDBC Connection for DDL execution. Please see server.log for more details.

Here are some files:

pom.xml:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.boraji.tutorial.spring</groupId>
  <artifactId>spring-mvc-hibernate-example</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  <properties>
    <failOnMissingWebXml>false</failOnMissingWebXml>
  </properties>
  <dependencies>
    <!-- Spring MVC Dependency -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>4.3.7.RELEASE</version>
    </dependency>

    <!-- Spring ORM -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-orm</artifactId>
      <version>4.3.7.RELEASE</version>
    </dependency>

    <!-- Mysql Connector -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>6.0.6</version>
    </dependency>

    <!-- Hibernate ORM -->
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-core</artifactId>
      <version>5.2.10.Final</version>
    </dependency>

    <!-- Hibernate-C3P0 Integration -->
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-c3p0</artifactId>
      <version>5.2.10.Final</version>
    </dependency>

    <!-- c3p0 -->
    <dependency>
      <groupId>com.mchange</groupId>
      <artifactId>c3p0</artifactId>
      <version>0.9.5.2</version>
    </dependency>

    <!-- Hibernate Validator -->
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-validator</artifactId>
      <version>5.4.1.Final</version>
    </dependency>

    <!-- JSTL Dependency -->
    <dependency>
      <groupId>javax.servlet.jsp.jstl</groupId>
      <artifactId>javax.servlet.jsp.jstl-api</artifactId>
      <version>1.2.1</version>
    </dependency>
    <dependency>
      <groupId>taglibs</groupId>
      <artifactId>standard</artifactId>
      <version>1.1.2</version>
    </dependency>

    <!-- Servlet Dependency -->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
      <scope>provided</scope>
    </dependency>

    <!-- JSP Dependency -->
    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>javax.servlet.jsp-api</artifactId>
      <version>2.3.1</version>
      <scope>provided</scope>
    </dependency>

    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate</artifactId>
      <version>3.5.4-Final</version>
    </dependency>
      <dependency>
          <groupId>org.slf4j</groupId>
          <artifactId>slf4j-log4j12</artifactId>
          <version>1.8.0-alpha2</version>
      </dependency>
  </dependencies>

</project>

Initializer:

public class MyWebAppInitializer
      extends AbstractAnnotationConfigDispatcherServletInitializer {

   @Override
   protected Class<?>[] getRootConfigClasses() {
      return new Class[] { AppConfig.class };
   }

   @Override
   protected Class<?>[] getServletConfigClasses() {
      return new Class[] { WebConfig.class };
   }

   @Override
   protected String[] getServletMappings() {
      return new String[] { "/" };
   }
}

application config:

@Configuration
@PropertySource("classpath:db.properties")
@EnableTransactionManagement
@ComponentScans(value = { @ComponentScan("com.boraji.tutorial.spring.dao"),
      @ComponentScan("com.boraji.tutorial.spring.service") })
public class AppConfig {

   @Autowired
   private Environment env;

   @Bean
   public LocalSessionFactoryBean getSessionFactory() {
      LocalSessionFactoryBean factoryBean = new LocalSessionFactoryBean();

      Properties props = new Properties();
      // Setting JDBC properties
      props.put(DRIVER, env.getProperty("mysql.driver"));
      props.put(URL, env.getProperty("mysql.url"));
      props.put(USER, env.getProperty("mysql.user"));
      props.put(PASS, env.getProperty("mysql.password"));

      // Setting Hibernate properties
      props.put(SHOW_SQL, env.getProperty("hibernate.show_sql"));
      props.put(HBM2DDL_AUTO, env.getProperty("hibernate.hbm2ddl.auto"));
      props.put(DIALECT, env.getProperty("hibernate.dialect"));

      // Setting C3P0 properties
      props.put(C3P0_MIN_SIZE, 
            env.getProperty("hibernate.c3p0.min_size"));
      props.put(C3P0_MAX_SIZE, 
            env.getProperty("hibernate.c3p0.max_size"));
      props.put(C3P0_ACQUIRE_INCREMENT,
            env.getProperty("hibernate.c3p0.acquire_increment"));
      props.put(C3P0_TIMEOUT, 
            env.getProperty("hibernate.c3p0.timeout"));
      props.put(C3P0_MAX_STATEMENTS, 
            env.getProperty("hibernate.c3p0.max_statements"));

      factoryBean.setHibernateProperties(props);
      factoryBean.setAnnotatedClasses(User.class);
      return factoryBean;
   }

   @Bean
   public HibernateTransactionManager getTransactionManager() {
      HibernateTransactionManager transactionManager = new HibernateTransactionManager();
      transactionManager.setSessionFactory(getSessionFactory().getObject());
      return transactionManager;
   }
}

db.properties:

# MySQL properties
mysql.driver=com.mysql.jdbc.Driver
mysql.url=jdbc:mysql://localhost/test
mysql.user=root
mysql.password=root

# Hibernate propert[2017-10-06 05:26:14,475] Artifact spring-mvc-hibernate-example:war: java.io.IOException: com.sun.enterprise.admin.remote.RemoteFailureException: Error occurred during deployment: Exception while loading the app : java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userDaoImp': Unsatisfied dependency expressed through field 'sessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'getSessionFactory' defined in com.boraji.tutorial.spring.config.AppConfig: Invocation of init method failed; nested exception is org.hibernate.exception.GenericJDBCException: Unable to open JDBC Connection for DDL execution. Please see server.log for more details.ies
hibernate.show_sql=true
hibernate.hbm2ddl.auto=update
hibernate.dialect=org.hibernate.dialect.MySQLDialect

#C3P0 properties
hibernate.c3p0.min_size=5
hibernate.c3p0.max_size=20
hibernate.c3p0.acquire_increment=1
hibernate.c3p0.timeout=1800
hibernate.c3p0.max_statements=150

UserDao:

@Repository
public class UserDaoImp implements UserDao {

   @Autowired
   private SessionFactory sessionFactory;


   public void save(User user) {
      sessionFactory.getCurrentSession().save(user);
   }


   public List<User> list() {
      @SuppressWarnings("unchecked")
      TypedQuery<User> query = sessionFactory.getCurrentSession().createQuery("from User");
      return query.getResultList();
   }

}

I saw lots of similar problems here but it didn’t help. What could go wrong in my application?

Android studio :java.lang.NoSuchMethodError: No static method zzz(Ljava/lang/Object;)Ljava/lang/Object;

I have a problem with the lib when i export the project from unity to AS I have tried pretty much all the similar solution in here but still cant solve. I used a play-service-measurement 8.4.0 in my project

30728-30728/app/AndroidRuntime: FATAL EXCEPTION: mainProcess: com.app, PID: 30728

                                                                java.lang.NoSuchMethodError: No static method zzz(Ljava/lang/Object;)Ljava/lang/Object; in class Lcom/google/android/gms/common/internal/zzx; or its super classes (declaration of 'com.google.android.gms.common.internal.zzx' appears in /data/app/xxxx/split_lib_dependencies_apk.apk)
                                                                    at com.google.android.gms.measurement.internal.zzw.zzaT(Unknown Source)
                                                                    at com.google.android.gms.measurement.AppMeasurementContentProvider.onCreate(Unknown Source)
                                                                    at android.content.ContentProvider.attachInfo(ContentProvider.java:1759)
                                                                    at android.content.ContentProvider.attachInfo(ContentProvider.java:1734)
                                                                    at android.app.ActivityThread.installProvider(ActivityThread.java:6420)
                                                                    at android.app.ActivityThread.installContentProviders(ActivityThread.java:6012)
                                                                    at android.app.ActivityThread.handleBindApplication(ActivityThread.java:5951)
                                                                    at android.app.ActivityThread.-wrap3(ActivityThread.java)
                                                                    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1710)
                                                                    at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                    at android.os.Looper.loop(Looper.java:154)
                                                                    at android.app.ActivityThread.main(ActivityThread.java:6776)
                                                                    at java.lang.reflect.Method.invoke(Native Method)
                                                                    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
                                                                    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)

How to check Before and After Date Times in Java for dates that are UTC in MySQL but for Multiple Time Zones?

Have a table setup in MySQL that holds data for an event (e.g. a music show or karaoke) at a particular place of business.

So my table looks like this:

CREATE TABLE `event_schedule` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `description` varchar(30) DEFAULT NULL,
  `event_id` varchar(30) NOT NULL DEFAULT,
  `event_date` datetime DEFAULT NULL,
  `event_date_time` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00'
)

Database table contains rows like this:

| 1 | karoake | aab3223  | 2017-08-15 00:00:00 | 2017-08-15 16:00:00 |
| 2 | comedy  | cce8465  | 2017-08-25 00:00:00 | 2017-08-25 19:00:00 | 

The event_date is in UTC Time format as well is the MySQL server that it resides in.

select now()

Will give time in UTC…

Have logic setup which uses a Spring JDBC to check if a particular row exists based on curdate() like this:

@Repository
public class EventDao {

    private static JdbcTemplate jdbcTemplate = null;

    @Autowired
    public EventDao(@Qualifier("aDataSource") DataSource dataSource) {
        EventDao.jdbcTemplateObject = new JdbcTemplate(dataSource);
    }

    public static String getEventId() {
        SqlRowSet eventRowSet = null;
        String eventId = "";
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
        dateInUTC = formatter.format(new Date());

        eventRowSet = jdbcTemplate.queryForRowSet(
            "select * from event_schedule where (event_date=CURDATE() or event_date=?)",
            new Object[] { dateInUTC });

        if (eventRowSet != null && eventRowSet.next()) {
            eventId = rst.getString("event_id");
        }
        return eventId;
    }
}

A class used to check if the event is under way:

 public class EventProcessor {

    public static String getEventStatus() {
        String eventId = getEventId();
        if (eventId != null) {
            return "Event Started";
        }
        else {
            return "Event not Started"
        }
        // TODO: Need to incorporate for two hours after its over.
        // "Event Ended"
    }
 }

This system seemed to be working when the requirements dependent on just the event_date in UTC was simply:

2017-08-15 00:00:00 

New Use Case(s) / Question(s):

If a client app connects to this web service and the situation is:

event starts 2017-08-15 19:00:00 (lets say this is 7:00 p.m PST) how can I set it up do this:

  1. Have the service return “Event Not Started” from 2017-08-14 00:00 to 2017-08-15 18:59:59 ?

Meaning, from the midnight of the same date until one minute before it starts?


  1. Have the service return “Event Ended” two hours after the event ends?

A lot of my client apps that connect to this web service might be in the West Coast (PST), Central (CST), or Eastern (EST).

  1. What is the best way to do a time conversion for them (since I am using UTC Datetimes in the MySQL Database and the MySQL Database is in UTC itself)?

How to check whether String is not equal to multiple other Strings ignoring case

I have a program that is asking a user for a day of the week. I am trying to test the answer given by the user and give them another chance to answer if they misspell a day or enter something else. My equals is either ignoring the Scanner before it or printing out the while statement no matter what day I put in.

System.out.println("Great! Welcome back " + cust.getName() + ". What day of the week would you like "
            + "to book?(Sunday, November the 12th thru Saturday, November the 18th");

    String day = scan.nextLine();
    String dayLower = day.toLowerCase();
    scan.nextLine();


    while (!"monday".equals(dayLower) && !dayLower.equals("tuesday") && !dayLower.equals("wednesday")
            && !dayLower.equals("thursday") && !dayLower.equals("friday") && !dayLower.equals("saturday")
            && !dayLower.equals("sunday")) {
        System.out.println("Error in entry. Please enter a day of the week.");
        day = scan.nextLine();
    }

Using log4j (1) separate messages by color

i am using log4j
i am trying to display the different levels of messages in different colors.

I have the colors for each level working, the problem is i get multiple messages

i found a couple of articles that suggested using org.apache.log4j.varia.LevelRangeFilter

but still does not work

my log4j.properties looks like

log4j.rootLogger=DEBUG,  StdoutInfo, StdoutWarn, StdoutDebug, StdoutErrorFatal


log4j.appender.StdoutWarn=org.apache.log4j.ConsoleAppender
log4j.appender.StdoutWarn.layout=org.apache.log4j.PatternLayout
log4j.appender.StdoutWarn.layout.conversionPattern=u001b[33;1m%-5p(%L) %m 1n
log4j.appender.StdoutWarn.Threshold=WARN
log4j.appender.StdoutWarn.filter.A=org.apache.log4j.varia.LevelRangeFilter
log4j.appender.StdoutWarn.filter.A.LevelMin=WARN
log4j.appender.StdoutWarn.filter.A.LevelMax=WARN

log4j.appender.StdoutInfo=org.apache.log4j.ConsoleAppender
log4j.appender.StdoutInfo.layout=org.apache.log4j.PatternLayout
log4j.appender.StdoutInfo.layout.conversionPattern=u001b[0m%-5p(%L) %m <-n
log4j.appender.StdoutInfo.Threshold=INFO
log4j.appender.StdoutInfo.filter.B=org.apache.log4j.varia.LevelRangeFilter
log4j.appender.StdoutInfo.filter.B.LevelMin=INFO
log4j.appender.StdoutInfo.filter.B.LevelMax=INFO


log4j.appender.StdoutDebug=org.apache.log4j.ConsoleAppender
log4j.appender.StdoutDebug.layout=org.apache.log4j.PatternLayout
log4j.appender.StdoutDebug.layout.conversionPattern=u001b[0;36m%-5p(%L) %m 3n
log4j.appender.StdoutDebug.Threshold=DEBUG
log4j.appender.StdoutDebug.filter.C=org.apache.log4j.varia.LevelRangeFilter
log4j.appender.StdoutDebug.filter.C.LevelMin=DEBUG
log4j.appender.StdoutDebug.filter.C.LevelMax=DEBUG


log4j.appender.StdoutErrorFatal=org.apache.log4j.ConsoleAppender
log4j.appender.StdoutErrorFatal.layout=org.apache.log4j.PatternLayout
log4j.appender.StdoutErrorFatal.layout.conversionPattern=u001b[31;1m%-5p(%L) %mn
log4j.appender.StdoutErrorFatal.threshold=ERROR
log4j.appender.StdoutErrorFatal.filter.D=org.apache.log4j.varia.LevelRangeFilter
log4j.appender.StdoutErrorFatal.filter.D.LevelMin=ERROR
log4j.appender.StdoutErrorFatal.filter.D.LevelMax=ERROR

on the console if i have a logger.info i see

WARN (242) The account appears not  to be a CCard  <-
WARN (242) The account appears not  to be a CCard  1
WARN (242) The account appears not  to be a CCard  3

the <-, 1,3 and the end i am using to help me determine which appender is being used

thanks for any help

I keep getting ‘Exception in thread “main” java.lang.NullPointerException’

The errors are with the writeToFile() method. I can comment it out and it runs perfectly without the Exception error. So basically, Im trying to get those Nutrition facts to print on a txt file.
The error looks like this

“Exception in thread “main” java.lang.NullPointerException

at Environment.writeToFile(Java1001.java:71)

at Environment.(Java1001.java:54)

at Java1001.main(Java1001.java:43)”

 import static java.lang.System.*;
    import java.io.*;

    public class Java1001
    {
        public static void main(String[] args) throws IOException
        {
            new Environment();
        } 
    }

    class Environment
    {
        private PrintStream outFile;

        public Environment()
        {
            createOutputStream();
            writeToFile();
        }

        public void createOutputStream()
        {
            // create outFile stream here
            File outFile = null;
            try
            {
                outFile = new File("Nutrition.txt");
                outFile.createNewFile();
            }
            catch (Exception e){}
        }

        public void writeToFile()
        {
            outFile.println("NUTRITION FACTS");
            outFile.println("======================================");
            outFile.println("Serving Size 1 tbsp (6g)");
            outFile.println("Servings Per Container about 4");
            outFile.println("======================================");
            outFile.println("Amount Per Serving");
            outFile.println("Calories           20");
            outFile.println("Calories from Fat  5");
            outFile.println("======================================");
            outFile.println("Total Fat 0.5g");
            outFile.println("Sodium 280mg");
            outFile.println("Total Carbohydrate 4g");
            outFile.println("Sugars 0g");
            outFile.println("Protein less than 1 g");
            outFile.println("======================================");
        }
    }