/*
Copyright 2015 Google Inc. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

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

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.google.security.zynamics.binnavi.Database.PostgreSQL.Creators;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;

import com.google.common.base.Preconditions;
import com.google.security.zynamics.binnavi.Database.AbstractSQLProvider;
import com.google.security.zynamics.binnavi.Database.CConnection;
import com.google.security.zynamics.binnavi.Database.CTableNames;
import com.google.security.zynamics.binnavi.Database.Exceptions.CouldntSaveDataException;
import com.google.security.zynamics.binnavi.Database.PostgreSQL.PostgreSQLHelpers;
import com.google.security.zynamics.binnavi.Log.NaviLogger;
import com.google.security.zynamics.binnavi.debug.debugger.DebuggerTemplate;
import com.google.security.zynamics.binnavi.disassembly.CProject;

public final class PostgreSQLProjectCreator {
  /**
   * You are not supposed to instantiate this class.
   */
  private PostgreSQLProjectCreator() {
    // You are not supposed to instantiate this class.
  }

  /**
   * Loads a project from the database.
   * 
   * @param provider The connection to the database.
   * @param projectId The ID of the project to load.
   * 
   * @return The loaded project.
   * 
   * @throws SQLException Thrown if the project could not be loaded.
   */
  protected static CProject loadProject(final AbstractSQLProvider provider, final int projectId)
      throws SQLException {
    final String query =
        "select id, name, description, creation_date, modification_date from "
            + CTableNames.PROJECTS_TABLE + " where id = " + projectId;

    final ResultSet resultSet = provider.getConnection().executeQuery(query, true);

    try {
      while (resultSet.next()) {
        final String name = PostgreSQLHelpers.readString(resultSet, "name");
        final String description = PostgreSQLHelpers.readString(resultSet, "description");
        final int addressSpaceCount = 0;
        final Timestamp creationDate = resultSet.getTimestamp("creation_date");
        final Timestamp modificationDate = resultSet.getTimestamp("modification_date");

        return new CProject(projectId, name, description, creationDate, modificationDate,
            addressSpaceCount, new ArrayList<DebuggerTemplate>(), provider);
      }
    } finally {
      resultSet.close();
    }

    return null;
  }

  /**
   * Creates a new project in the database.
   * 
   * @param provider The SQL provider that provides the connection.
   * @param name The name of the new project.
   * 
   * @return The created project.
   * 
   * @throws CouldntSaveDataException Thrown if the project could not be created.
   */
  public static CProject createProject(final AbstractSQLProvider provider, final String name)
      throws CouldntSaveDataException {
    Preconditions.checkNotNull(provider, "IE00513: Provider argument can not be null");
    Preconditions.checkNotNull(name, "IE00514: Project names can not be null");
    Preconditions.checkArgument(!("".equals(name)), "IE00515: Project names can not be empty");

    final CConnection connection = provider.getConnection();

    NaviLogger.info("Creating new project %s", name);

    try {
      final String query =

          "INSERT INTO "
              + CTableNames.PROJECTS_TABLE
              + "(name, description, creation_date, modification_date) VALUES(?, '', NOW(), NOW()) RETURNING id";


      final PreparedStatement statement =
          connection.getConnection().prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE,
              ResultSet.CONCUR_READ_ONLY);

      try {
        statement.setString(1, name);

        final ResultSet resultSet = statement.executeQuery();

        Integer id = null;

        try {
          while (resultSet.next()) {
            if (resultSet.isFirst()) {
              id = resultSet.getInt(1);
              break;
            }
          }
        } finally {
          resultSet.close();
        }
        Preconditions.checkNotNull(id,
            "IE02044: Error id for a project after creation may not be null");

        return PostgreSQLProjectCreator.loadProject(provider, id);
      } finally {
        statement.close();
      }
    } catch (final SQLException e) {
      throw new CouldntSaveDataException(e);
    }
  }
}

@@ -2213,30 +2213,29 @@
 ectId;%0A%0A    
-final 
+try (
 ResultSet re
@@ -2294,26 +2294,17 @@
 y, true)
-;%0A%0A    try
+)
  %7B%0A     
@@ -2888,55 +2888,18 @@
   %7D%0A
-    %7D finally %7B%0A      resultSet.close();%0A
     %7D%0A
+    
 %0A   
@@ -3958,29 +3958,29 @@
 G id%22;%0A%0A
-%0A
       
-final 
+  try (
 Prepared
@@ -4144,73 +4144,18 @@
 Y);%0A
-%0A
       
-try %7B%0A        statement.setString(1, name);%0A%0A        final
+    
  Res
@@ -4197,16 +4197,56 @@
 eQuery()
+) %7B%0A        statement.setString(1, name)
 ;%0A%0A     
@@ -4272,22 +4272,8 @@
 l;%0A%0A
-        try %7B%0A
     
@@ -4443,58 +4443,8 @@
     
-%7D finally %7B%0A          resultSet.close();%0A        %7D
 %0A   
@@ -4630,61 +4630,8 @@
 d);%0A
-      %7D finally %7B%0A        statement.close();%0A      %7D%0A
     

Update PostgreSQLProjectCreator.java