    /**
     * returns all statuses
     *
     * @param con DB connection object
     * @param userId user id
     */
    private static List<HostSystem> getAllSystemStatus(Connection con, Long userId) {

        List<HostSystem> hostSystemList = new ArrayList<>();
        try {

            PreparedStatement stmt = con.prepareStatement("select * from status where user_id=? order by id asc");
            stmt.setLong(1, userId);
            ResultSet rs = stmt.executeQuery();

            while (rs.next()) {
                HostSystem hostSystem = SystemDB.getSystem(con, rs.getLong("id"));
                hostSystem.setStatusCd(rs.getString("status_cd"));
                hostSystemList.add(hostSystem);
            }
            DBUtils.closeRs(rs);
            DBUtils.closeStmt(stmt);

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

    }

    /**
     * returns all statuses
     *
     * @param con DB connection object
     * @param userId user id
     */
    private static List<HostSystem> getAllSystemStatus(Connection con, Long userId) {

        List<HostSystem> hostSystemList = new ArrayList<HostSystem>();
        try {

            PreparedStatement stmt = con.prepareStatement("select * from status where user_id=? order by id asc");
            stmt.setLong(1, userId);
            ResultSet rs = stmt.executeQuery();

            while (rs.next()) {
                HostSystem hostSystem = SystemDB.getSystem(con, rs.getLong("id"));
                hostSystem.setStatusCd(rs.getString("status_cd"));
                hostSystemList.add(hostSystem);
            }
            DBUtils.closeRs(rs);
            DBUtils.closeStmt(stmt);

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

    }

Replace Generic With Diamond ArrayList<HostSystem> with ArrayList<> in method private getAllSystemStatus(con Connection, userId Long) : List<HostSystem> from class com.ec2box.manage.db.SystemStatusDB


    /**
     * returns users based on sort order defined
     * @param sortedSet object that defines sort order
     * @return sorted user list
     */
    public static SortedSet getUserSet(SortedSet sortedSet) {

        ArrayList<User> userList = new ArrayList<>();

        String orderBy = "";
        if (sortedSet.getOrderByField() != null && !sortedSet.getOrderByField().trim().equals("")) {
            orderBy = "order by " + sortedSet.getOrderByField() + " " + sortedSet.getOrderByDirection();
        }
        String sql = "select * from  users where enabled=true " + orderBy;

        Connection con = null;
        try {
            con = DBUtils.getConn();
            PreparedStatement stmt = con.prepareStatement(sql);
            ResultSet rs = stmt.executeQuery();

            while (rs.next()) {
                User user = new User();
                user.setId(rs.getLong("id"));
                user.setFirstNm(rs.getString("first_nm"));
                user.setLastNm(rs.getString("last_nm"));
                user.setEmail(rs.getString("email"));
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                user.setUserType(rs.getString("user_type"));
                userList.add(user);

            }
            DBUtils.closeRs(rs);
            DBUtils.closeStmt(stmt);

        } catch (Exception e) {
            e.printStackTrace();
        }
        DBUtils.closeConn(con);

        sortedSet.setItemList(userList);
        return sortedSet;
    }

    /**
     * returns users based on sort order defined
     * @param sortedSet object that defines sort order
     * @return sorted user list
     */
    public static SortedSet getUserSet(SortedSet sortedSet) {

        ArrayList<User> userList = new ArrayList<User>();

        String orderBy = "";
        if (sortedSet.getOrderByField() != null && !sortedSet.getOrderByField().trim().equals("")) {
            orderBy = "order by " + sortedSet.getOrderByField() + " " + sortedSet.getOrderByDirection();
        }
        String sql = "select * from  users where enabled=true " + orderBy;

        Connection con = null;
        try {
            con = DBUtils.getConn();
            PreparedStatement stmt = con.prepareStatement(sql);
            ResultSet rs = stmt.executeQuery();

            while (rs.next()) {
                User user = new User();
                user.setId(rs.getLong("id"));
                user.setFirstNm(rs.getString("first_nm"));
                user.setLastNm(rs.getString("last_nm"));
                user.setEmail(rs.getString("email"));
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                user.setUserType(rs.getString("user_type"));
                userList.add(user);

            }
            DBUtils.closeRs(rs);
            DBUtils.closeStmt(stmt);

        } catch (Exception e) {
            e.printStackTrace();
        }
        DBUtils.closeConn(con);

        sortedSet.setItemList(userList);
        return sortedSet;
    }

Replace Generic With Diamond ArrayList<User> with ArrayList<> in method public getUserSet(sortedSet SortedSet) : SortedSet from class com.ec2box.manage.db.UserDB


    /**
     * return a list of profiles for user
     * @param userId user id
     * @return profile list
     */
    public static List<Profile> getProfilesByUser(Long userId) {

        Connection con = null;
        List<Profile> profileList = new ArrayList<>();
        try {
            con = DBUtils.getConn();
            profileList = getProfilesByUser(con, userId);

        } catch (Exception e) {
            e.printStackTrace();
        }
        DBUtils.closeConn(con);
        return profileList;

    }

    /**
     * return a list of profiles for user
     * @param userId user id
     * @return profile list
     */
    public static List<Profile> getProfilesByUser(Long userId) {

        Connection con = null;
        List<Profile> profileList = new ArrayList<Profile>();
        try {
            con = DBUtils.getConn();
            profileList = getProfilesByUser(con, userId);

        } catch (Exception e) {
            e.printStackTrace();
        }
        DBUtils.closeConn(con);
        return profileList;

    }

Replace Generic With Diamond ArrayList<Profile> with ArrayList<> in method public getProfilesByUser(userId Long) : List<Profile> from class com.ec2box.manage.db.UserProfileDB


    /**
     * return a list of profiles for user
     * @param userId user id
     * @return profile list
     */
    public static List<Profile> getProfilesByUser(Connection con, Long userId) {

        ArrayList<Profile> profileList = new ArrayList<>();

        try {
            PreparedStatement stmt = con.prepareStatement("select * from  profiles g, user_map m where g.id=m.profile_id and m.user_id=? order by nm asc");
            stmt.setLong(1, userId);
            ResultSet rs = stmt.executeQuery();

            while (rs.next()) {
                Profile profile = new Profile();
                profile.setId(rs.getLong("id"));
                profile.setNm(rs.getString("nm"));
                profile.setTag(rs.getString("tag"));
                profileList.add(profile);
            }
            DBUtils.closeRs(rs);
            DBUtils.closeStmt(stmt);

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

        return profileList;
    }

    /**
     * return a list of profiles for user
     * @param userId user id
     * @return profile list
     */
    public static List<Profile> getProfilesByUser(Connection con, Long userId) {

        ArrayList<Profile> profileList = new ArrayList<Profile>();

        try {
            PreparedStatement stmt = con.prepareStatement("select * from  profiles g, user_map m where g.id=m.profile_id and m.user_id=? order by nm asc");
            stmt.setLong(1, userId);
            ResultSet rs = stmt.executeQuery();

            while (rs.next()) {
                Profile profile = new Profile();
                profile.setId(rs.getLong("id"));
                profile.setNm(rs.getString("nm"));
                profile.setTag(rs.getString("tag"));
                profileList.add(profile);
            }
            DBUtils.closeRs(rs);
            DBUtils.closeStmt(stmt);

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

        return profileList;
    }

Replace Generic With Diamond ArrayList<Profile> with ArrayList<> in method public getProfilesByUser(con Connection, userId Long) : List<Profile> from class com.ec2box.manage.db.UserProfileDB


    /**
     * get users associated with profile
     * @param profileId profile id
     * @return user list
     */
    public static List<User> getUsersByProfile(Long profileId) {

        Connection con = null;
        List<User> userList = new ArrayList<>();
        try {
            con = DBUtils.getConn();
            userList = getUsersByProfile(con, profileId);

        } catch (Exception e) {
            e.printStackTrace();
        }
        DBUtils.closeConn(con);
        return userList;

    }

    /**
     * get users associated with profile
     * @param profileId profile id
     * @return user list
     */
    public static List<User> getUsersByProfile(Long profileId) {

        Connection con = null;
        List<User> userList = new ArrayList<User>();
        try {
            con = DBUtils.getConn();
            userList = getUsersByProfile(con, profileId);

        } catch (Exception e) {
            e.printStackTrace();
        }
        DBUtils.closeConn(con);
        return userList;

    }

Replace Generic With Diamond ArrayList<User> with ArrayList<> in method public getUsersByProfile(profileId Long) : List<User> from class com.ec2box.manage.db.UserProfileDB


    /**
     * get users associated with profile
     * @param con DB connection
     * @param profileId profile id
     * @return user list
     */
    public static List<User> getUsersByProfile(Connection con, Long profileId) {

        ArrayList<User> userList = new ArrayList<>();

        try {
            PreparedStatement stmt = con.prepareStatement("select * from  users u, user_map m where u.id=m.user_id and m.profile_id=? order by last_nm asc");
            stmt.setLong(1, profileId);
            ResultSet rs = stmt.executeQuery();

            while (rs.next()) {
                User user = new User();
                user.setId(rs.getLong("id"));
                user.setFirstNm(rs.getString("first_nm"));
                user.setLastNm(rs.getString("last_nm"));
                user.setEmail(rs.getString("email"));
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                userList.add(user);
            }
            DBUtils.closeRs(rs);
            DBUtils.closeStmt(stmt);

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

        return userList;
    }

    /**
     * get users associated with profile
     * @param con DB connection
     * @param profileId profile id
     * @return user list
     */
    public static List<User> getUsersByProfile(Connection con, Long profileId) {

        ArrayList<User> userList = new ArrayList<User>();

        try {
            PreparedStatement stmt = con.prepareStatement("select * from  users u, user_map m where u.id=m.user_id and m.profile_id=? order by last_nm asc");
            stmt.setLong(1, profileId);
            ResultSet rs = stmt.executeQuery();

            while (rs.next()) {
                User user = new User();
                user.setId(rs.getLong("id"));
                user.setFirstNm(rs.getString("first_nm"));
                user.setLastNm(rs.getString("last_nm"));
                user.setEmail(rs.getString("email"));
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                userList.add(user);
            }
            DBUtils.closeRs(rs);
            DBUtils.closeStmt(stmt);

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

        return userList;
    }

Replace Generic With Diamond ArrayList<User> with ArrayList<> in method public getUsersByProfile(con Connection, profileId Long) : List<User> from class com.ec2box.manage.db.UserProfileDB


    /**
     * returns list of output lines
     *
     * @param sessionId session id object
     * @return session output list
     */
    public static List<SessionOutput> getOutput(Connection con, Long sessionId, User user) {
        List<SessionOutput> outputList = new ArrayList<>();

        UserSessionsOutput userSessionsOutput = userSessionsOutputMap.get(sessionId);
        if (userSessionsOutput != null) {

            for (Integer key : userSessionsOutput.getSessionOutputMap().keySet()) {

                //get output chars and set to output
                try {
                    SessionOutput sessionOutput = userSessionsOutput.getSessionOutputMap().get(key);
                    if (sessionOutput!=null && sessionOutput.getOutput() != null) {

                        if (StringUtils.isNotEmpty(sessionOutput.getOutput())) {
                            outputList.add(sessionOutput);

                            //send to audit logger
                            systemAuditLogger.info(gson.toJson(new AuditWrapper(user, sessionOutput)));

                            if(enableInternalAudit) {
                                SessionAuditDB.insertTerminalLog(con, sessionOutput);
                            }

                            userSessionsOutput.getSessionOutputMap().put(key, new SessionOutput(sessionId, sessionOutput));
                        }
                    }
                } catch (Exception ex) {
                    log.error(ex.toString(), ex);
                }

            }

        }

        return outputList;
    }

    /**
     * returns list of output lines
     *
     * @param sessionId session id object
     * @return session output list
     */
    public static List<SessionOutput> getOutput(Connection con, Long sessionId, User user) {
        List<SessionOutput> outputList = new ArrayList<SessionOutput>();

        UserSessionsOutput userSessionsOutput = userSessionsOutputMap.get(sessionId);
        if (userSessionsOutput != null) {

            for (Integer key : userSessionsOutput.getSessionOutputMap().keySet()) {

                //get output chars and set to output
                try {
                    SessionOutput sessionOutput = userSessionsOutput.getSessionOutputMap().get(key);
                    if (sessionOutput!=null && sessionOutput.getOutput() != null) {

                        if (StringUtils.isNotEmpty(sessionOutput.getOutput())) {
                            outputList.add(sessionOutput);

                            //send to audit logger
                            systemAuditLogger.info(gson.toJson(new AuditWrapper(user, sessionOutput)));

                            if(enableInternalAudit) {
                                SessionAuditDB.insertTerminalLog(con, sessionOutput);
                            }

                            userSessionsOutput.getSessionOutputMap().put(key, new SessionOutput(sessionId, sessionOutput));
                        }
                    }
                } catch (Exception ex) {
                    log.error(ex.toString(), ex);
                }

            }

        }

        return outputList;
    }

Replace Generic With Diamond ArrayList<SessionOutput> with ArrayList<> in method public getOutput(con Connection, sessionId Long, user User) : List<SessionOutput> from class com.ec2box.manage.util.SessionOutputUtil


    private ResponseEntity<?> imageResourceResponse(byte[] content, MediaType mediaType) {
        return new ResponseEntity<>(content, responseHeader(content, mediaType), OK);
    }

    private ResponseEntity<?> imageResourceResponse(byte[] content, MediaType mediaType) {
        return new ResponseEntity<byte[]>(content, responseHeader(content, mediaType), OK);
    }

Replace Generic With Diamond ResponseEntity<byte[]> with ResponseEntity<> in method private imageResourceResponse(content byte[], mediaType MediaType) : ResponseEntity<?> from class org.lightadmin.core.web.util.ImageResourceControllerSupport


        @Override
        protected List<URL> getSourceURLs(TilesApplicationContext applicationContext,
                                          TilesRequestContextFactory contextFactory) {
            if (definitions != null) {
                try {
                    List<URL> result = new LinkedList<>();
                    for (String definition : definitions) {
                        result.addAll(applicationContext.getResources(definition));
                    }
                    return result;
                } catch (IOException ex) {
                    throw new DefinitionsFactoryException("Cannot load definition URLs", ex);
                }
            } else {
                return super.getSourceURLs(applicationContext, contextFactory);
            }
        }

        @Override
        protected List<URL> getSourceURLs(TilesApplicationContext applicationContext,
                                          TilesRequestContextFactory contextFactory) {
            if (definitions != null) {
                try {
                    List<URL> result = new LinkedList<URL>();
                    for (String definition : definitions) {
                        result.addAll(applicationContext.getResources(definition));
                    }
                    return result;
                } catch (IOException ex) {
                    throw new DefinitionsFactoryException("Cannot load definition URLs", ex);
                }
            } else {
                return super.getSourceURLs(applicationContext, contextFactory);
            }
        }

Replace Generic With Diamond LinkedList<URL> with LinkedList<> in method protected getSourceURLs(applicationContext TilesApplicationContext, contextFactory TilesRequestContextFactory) : List<URL> from class org.lightadmin.core.view.LightAdminSpringTilesInitializer.SpringTilesContainerFactory


        @Override
        protected DefinitionsReader createDefinitionsReader(TilesApplicationContext applicationContext,
                                                            TilesRequestContextFactory contextFactory) {
            DigesterDefinitionsReader reader = new DigesterDefinitionsReader();
            Map<String, String> map = new HashMap<>();
            map.put(DigesterDefinitionsReader.PARSER_VALIDATE_PARAMETER_NAME, Boolean.FALSE.toString());
            reader.init(map);
            return reader;
        }

        @Override
        protected DefinitionsReader createDefinitionsReader(TilesApplicationContext applicationContext,
                                                            TilesRequestContextFactory contextFactory) {
            DigesterDefinitionsReader reader = new DigesterDefinitionsReader();
            Map<String, String> map = new HashMap<String, String>();
            map.put(DigesterDefinitionsReader.PARSER_VALIDATE_PARAMETER_NAME, Boolean.FALSE.toString());
            reader.init(map);
            return reader;
        }

Replace Generic With Diamond HashMap<String,String> with HashMap<> in method protected createDefinitionsReader(applicationContext TilesApplicationContext, contextFactory TilesRequestContextFactory) : DefinitionsReader from class org.lightadmin.core.view.LightAdminSpringTilesInitializer.SpringTilesContainerFactory


  private static List<String> getWeights(String plugin, SubnodeConfiguration work) {

    List<String> weight_strings = new LinkedList<>();
    @SuppressWarnings("unchecked")
    List<SubnodeConfiguration> weights = work.configurationsAt("weights");
    boolean weights_started = false;

    for (SubnodeConfiguration weight : weights) {
      // stop if second attributed node encountered
      if (weights_started && weight.getRootNode().getAttributeCount() > 0) {
          break;
      }
      // start adding node values, if node with attribute equal to current
      // plugin encountered
      if (weight.getRootNode().getAttributeCount() > 0 &&
          weight.getRootNode().getAttribute(0).getValue().equals(plugin)) {
          weights_started = true;
      }
      if (weights_started) {
          weight_strings.add(weight.getString(""));
      }
    }
    return weight_strings;
  }

  private static List<String> getWeights(String plugin, SubnodeConfiguration work) {

    List<String> weight_strings = new LinkedList<String>();
    @SuppressWarnings("unchecked")
    List<SubnodeConfiguration> weights = work.configurationsAt("weights");
    boolean weights_started = false;

    for (SubnodeConfiguration weight : weights) {
      // stop if second attributed node encountered
      if (weights_started && weight.getRootNode().getAttributeCount() > 0) {
          break;
      }
      // start adding node values, if node with attribute equal to current
      // plugin encountered
      if (weight.getRootNode().getAttributeCount() > 0 &&
          weight.getRootNode().getAttribute(0).getValue().equals(plugin)) {
          weights_started = true;
      }
      if (weights_started) {
          weight_strings.add(weight.getString(""));
      }
    }
    return weight_strings;
  }

Replace Generic With Diamond LinkedList<String> with LinkedList<> in method private getWeights(plugin String, work SubnodeConfiguration) : List<String> from class com.oltpbenchmark.DBWorkload


  public Customer getCustomerByName(int c_w_id, int c_d_id, String c_last) throws SQLException {
    ArrayList<Customer> customers = new ArrayList<>();
    boolean trace = LOG.isDebugEnabled();

    customerByName.setInt(1, c_w_id);
    customerByName.setInt(2, c_d_id);
    customerByName.setString(3, c_last);
    if (trace) LOG.trace("customerByName START");
    ResultSet rs = customerByName.executeQuery();
    if (trace) LOG.trace("customerByName END");

    while (rs.next()) {
      Customer c = TPCCUtil.newCustomerFromResults(rs);
      c.c_id = rs.getInt("C_ID");
      c.c_last = c_last;
      customers.add(c);
    }
    rs.close();

    if (customers.size() == 0) {
      String msg = String.format("Failed to get CUSTOMER [C_W_ID=%d, C_D_ID=%d, C_LAST=%s]",
                                 c_w_id, c_d_id, c_last);
      if (trace) LOG.warn(msg);
      throw new RuntimeException(msg);
    }

    // TPC-C 2.5.2.2: Position n / 2 rounded up to the next integer, but
    // that counts starting from 1.
    int index = customers.size() / 2;
    if (customers.size() % 2 == 0) {
        index -= 1;
    }
    return customers.get(index);
  }

  public Customer getCustomerByName(int c_w_id, int c_d_id, String c_last) throws SQLException {
    ArrayList<Customer> customers = new ArrayList<Customer>();
    boolean trace = LOG.isDebugEnabled();

    customerByName.setInt(1, c_w_id);
    customerByName.setInt(2, c_d_id);
    customerByName.setString(3, c_last);
    if (trace) LOG.trace("customerByName START");
    ResultSet rs = customerByName.executeQuery();
    if (trace) LOG.trace("customerByName END");

    while (rs.next()) {
      Customer c = TPCCUtil.newCustomerFromResults(rs);
      c.c_id = rs.getInt("C_ID");
      c.c_last = c_last;
      customers.add(c);
    }
    rs.close();

    if (customers.size() == 0) {
      String msg = String.format("Failed to get CUSTOMER [C_W_ID=%d, C_D_ID=%d, C_LAST=%s]",
                                 c_w_id, c_d_id, c_last);
      if (trace) LOG.warn(msg);
      throw new RuntimeException(msg);
    }

    // TPC-C 2.5.2.2: Position n / 2 rounded up to the next integer, but
    // that counts starting from 1.
    int index = customers.size() / 2;
    if (customers.size() % 2 == 0) {
        index -= 1;
    }
    return customers.get(index);
  }

Replace Generic With Diamond ArrayList<Customer> with ArrayList<> in method public getCustomerByName(c_w_id int, c_d_id int, c_last String) : Customer from class com.oltpbenchmark.benchmarks.tpcc.procedures.OrderStatus


  public Customer getCustomerByName(int c_w_id, int c_d_id,
                                    String customerLastName) throws SQLException {
    ArrayList<Customer> customers = new ArrayList<>();
    customerByName.setInt(1, c_w_id);
    customerByName.setInt(2, c_d_id);
    customerByName.setString(3, customerLastName);
    ResultSet rs = customerByName.executeQuery();
    if (LOG.isTraceEnabled())
      LOG.trace("C_LAST=" + customerLastName + " C_D_ID=" + c_d_id + " C_W_ID=" + c_w_id);

    while (rs.next()) {
      Customer c = TPCCUtil.newCustomerFromResults(rs);
      c.c_id = rs.getInt("C_ID");
      c.c_last = customerLastName;
      customers.add(c);
    }
    rs.close();

    if (customers.size() == 0) {
      throw new RuntimeException("C_LAST=" + customerLastName + " C_D_ID=" + c_d_id + " C_W_ID=" +
                                 c_w_id + " not found!");
    }

    // TPC-C 2.5.2.2: Position n / 2 rounded up to the next integer, but
    // that
    // counts starting from 1.
    int index = customers.size() / 2;
    if (customers.size() % 2 == 0) {
      index -= 1;
    }
    return customers.get(index);
  }

  public Customer getCustomerByName(int c_w_id, int c_d_id,
                                    String customerLastName) throws SQLException {
    ArrayList<Customer> customers = new ArrayList<Customer>();
    customerByName.setInt(1, c_w_id);
    customerByName.setInt(2, c_d_id);
    customerByName.setString(3, customerLastName);
    ResultSet rs = customerByName.executeQuery();
    if (LOG.isTraceEnabled())
      LOG.trace("C_LAST=" + customerLastName + " C_D_ID=" + c_d_id + " C_W_ID=" + c_w_id);

    while (rs.next()) {
      Customer c = TPCCUtil.newCustomerFromResults(rs);
      c.c_id = rs.getInt("C_ID");
      c.c_last = customerLastName;
      customers.add(c);
    }
    rs.close();

    if (customers.size() == 0) {
      throw new RuntimeException("C_LAST=" + customerLastName + " C_D_ID=" + c_d_id + " C_W_ID=" +
                                 c_w_id + " not found!");
    }

    // TPC-C 2.5.2.2: Position n / 2 rounded up to the next integer, but
    // that
    // counts starting from 1.
    int index = customers.size() / 2;
    if (customers.size() % 2 == 0) {
      index -= 1;
    }
    return customers.get(index);
  }

Replace Generic With Diamond ArrayList<Customer> with ArrayList<> in method public getCustomerByName(c_w_id int, c_d_id int, customerLastName String) : Customer from class com.oltpbenchmark.benchmarks.tpcc.procedures.Payment


    /**
     * Convenience class method for constructing pairs using Java's generic type
     * inference.
     */
    public static <T, U> Pair<T, U> of(T x, U y) {
        return new Pair<>(x, y);
    }

    /**
     * Convenience class method for constructing pairs using Java's generic type
     * inference.
     */
    public static <T, U> Pair<T, U> of(T x, U y) {
        return new Pair<T, U>(x, y);
    }

Replace Generic With Diamond Pair<T,U> with Pair<> in method public of(x T, y U) : Pair<T,U> from class com.oltpbenchmark.util.Pair


    public void iniciar(GC gestor) throws InterruptedException
    {
        // Inicio el gestor
        try( ZContext context = new ZContext())
        {
            System.out.println();
            System.out.println("------------------INICIANDO PROCESO HOMOLOGO----------------");

            // Vincular con el puerto local para recibir las request de procesos solicitantes
            ZMQ.Socket socket = context.createSocket(SocketType.REP);
            socket.bind("tcp://10.43.100.136:5555");

            // Vincular con un puerto para publicar los topicos
            ZMQ.Socket publisher = context.createSocket(SocketType.PUB);
            publisher.bind("tcp://10.43.100.136:5556");

            // Conexion con un puerto para la operacion de solicitar
            ZMQ.Socket socketSolicitar = context.createSocket(SocketType.REQ);
            socketSolicitar.connect("tcp://10.43.100.136:5557");

            // Variables auxiliares para recibir valores
            String respuesta;
            String topico;

            while (!Thread.currentThread().isInterrupted())
            {
                // Se recibe el mensaje del proceso solicitante
                byte[] reply = socket.recv(0);
                String solicitud = new String(reply, ZMQ.CHARSET); // Se genera un string con la solicitud con formato: accion, codigo

                // Se guarda la informacion de la solicitud
                String[] elemSolicitud = solicitud.split(" ");
                String accion = elemSolicitud[0];
                int codigo = Integer.parseInt(elemSolicitud[1]);
                int sede = Integer.parseInt(elemSolicitud[2]);

                // Informe de la solicitud
                System.out.println("\n////////////////////////////////////////////////////////////");
                System.out.println("Mensaje del proceso solicitante: operacion - " + accion + ", codigo - " + codigo + ", sede - " + sede);

                // Dependiendo de la solicitud se realizara una accion
                if(accion.equalsIgnoreCase("devolver")){

                    respuesta = "\nBibilioteca recibiendo libro con codigo " + codigo + " desde la sede "+ sede + "...\n";

                    // Aceptar de forma inmediata la operacion y devolver una respusesta positva
                    System.out.println("Devolviendo respuesta al proceso solicitante...");
                    socket.send(respuesta.getBytes(ZMQ.CHARSET), 0);

                    // Publicar informacion del requerimiento
                    topico = "Devolucion";
                    publisher.send(topico + " " + codigo); //Se envia: topico, codigo
                }
                else if(accion.equalsIgnoreCase("renovar")){

                    // Configurar el formato de la fecha
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

                    // Obtener la fecha actual
                    Calendar c = Calendar.getInstance();
                    Calendar a = Calendar.getInstance();

                    // Aplicar la fecha
                    c.setTime(new Date());
                    a.setTime(new Date());
                    c.add(Calendar.DATE, 7); // Añadir la nueva fecha de entrega (1 semana apartir de la fecha actual)

                    // Guardar en una cadena de caracteres la fecha
                    String fechaEntrega = sdf.format(c.getTime());
                    String fechaActual = sdf.format(a.getTime());

                    respuesta = "\nBiblioteca renovando el prestamo con codigo " + codigo + " desde la sede "+ sede + "...\nLa fecha actual es: " + fechaActual + "\nLa nueva fecha de entrega es: " + fechaEntrega +"\n";

                    // Aceptar de forma inmediata la operacion y devolver una respusesta positva
                    System.out.println("Devolviendo respuesta al proceso solicitante...");
                    socket.send(respuesta.getBytes(ZMQ.CHARSET), 0);

                    // Publicar informacion del requerimiento
                    topico = "Renovacion";
                    publisher.send(topico + " " + codigo + " " + fechaActual + " " + fechaEntrega); // Se envia: topico, codigo, fecha actual, fecha nueva de entrega
                }
                else if(accion.equalsIgnoreCase("solicitar"))
                {
                    // Asignarle el trabajo al ActorSolicitar
                    socketSolicitar.send(solicitud.getBytes(ZMQ.CHARSET), 0);

                    // Se obtiene la respuesta del actorSolicitar
                    byte[] replySolicitar = socketSolicitar.recv(0);
                    System.out.println("Mensaje recibido del actor: " + new String(replySolicitar, ZMQ.CHARSET) + " desde la sede "+ sede);

                    // Enviar la respuesta al proceso solicitante
                    System.out.println("Devolviendo respuesta al proceso solicitante...");
                    System.out.println("////////////////////////////////////////////////////////////\n");
                    String respuestaSolicitante = new String(replySolicitar, ZMQ.CHARSET);
                    respuestaSolicitante = respuestaSolicitante + " desde la sede "+ sede +"\n";
                    socket.send(respuestaSolicitante.getBytes(ZMQ.CHARSET), 0); // Se envia la respuesta al proceso solicitante
                }
                else{
                    System.out.println("Operacion no soportada, las operaciones validas son: ");
                    System.out.println("devolver,<codigo del prestamo>,<numero de la sede>");
                    System.out.println("renovar,<codigo del prestamo>,<numero de la sede>");
                    System.out.println("solicitar,<codigo del libro>,<numero de la sede>");
                }

                 // Configurar el tiempo de espera
                Thread.sleep(1000); // Tiempo de espera para hacer el trabajo
            }

        } catch (InterruptedException e) {

            // Se informa la falla del gestor
            System.out.println();
            System.out.println("\nFalla del gestor: ");
            e.printStackTrace();
            System.out.println();

            // Se cierran los sockets y el contexto para liberar recursos
            gestor.getSocket().close();
            gestor.getPublisher().close();
            gestor.getSocketSolicitar().close();
            gestor.getContext().close();
        }
        catch (org.zeromq.ZMQException e) {

           // Se informa la falla del gestor
           System.out.println();
           System.err.println("\nFalla del gestor, excepción de ZeroMQ: " + e.getMessage());
           e.printStackTrace();
           System.out.println();

           // Se cierran los sockets y el contexto para liberar recursos
           gestor.getSocket().close();
           gestor.getPublisher().close();
           gestor.getSocketSolicitar().close();
           gestor.getContext().close();
        }
    }

    public void iniciar(GC gestor) throws InterruptedException
    {

        ZContext context = new ZContext();

        System.out.println("------------------INICIANDO GESTOR----------------");
        // Vincular con el puerto de los procesos solicitantes
        ZMQ.Socket socket = context.createSocket(SocketType.REP);
        // puerto de los procesos solicitantes
        // socket.bind("tcp://10.43.100.136:5555");
        //puerto local
        socket.bind("tcp://10.43.100.136:5555");

        // Vincular con un puerto para publicar los topicos
        ZMQ.Socket publisher = context.createSocket(SocketType.PUB);
        publisher.bind("tcp://10.43.100.136:5556");

        // Conexion con un puerto para la operacion de solicitar
        ZMQ.Socket socketSolicitar = context.createSocket(SocketType.REQ);
        socketSolicitar.connect("tcp://10.43.100.136:5557");

        // Inicio el gestor
        try {

            System.out.println("entre aqui");
            // Variables auxiliares para recibir valores
            String respuesta;
            String topico;

            while (!Thread.currentThread().isInterrupted())
            {
                System.out.println("entre while ..... ");
                // Se recibe el mensaje del proceso solicitante
                byte[] reply = socket.recv(0);
                String solicitud = new String(reply, ZMQ.CHARSET); // Se genera un string con la solicitud con formato: accion, codigo

                System.out.println("llego la solicitud: " + solicitud);

                // Se guarda la informacion de la solicitud
                String[] elemSolicitud = solicitud.split(" ");
                String accion = elemSolicitud[0];
                int codigo = Integer.parseInt(elemSolicitud[1]);
                int sede = Integer.parseInt(elemSolicitud[2]);

                System.out.println("\n////////////////////////////////////////////////////////////");
                System.out.println("Mensaje del proceso solicitante: operacion - " + accion + ", codigo - " + codigo + ", sede - " + sede);

                // Dependiendo de la solicitud se realizara una accion
                if(accion.equalsIgnoreCase("devolver")){

                    respuesta = "\nBibilioteca recibiendo libro con codigo " + codigo + " desde la sede "+ sede + "...\n";

                    // Aceptar de forma inmediata la operacion y devolver una respusesta positva
                    System.out.println("Devolviendo respuesta al proceso solicitante...");
                    socket.send(respuesta.getBytes(ZMQ.CHARSET), 0);

                    // Publicar informacion del requerimiento
                    topico = "Devolucion";
                    publisher.send(topico + " " + codigo); //Se envia: topico, codigo
                }
                else if(accion.equalsIgnoreCase("renovar")){

                    // Configurar el formato de la fecha
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

                    // Obtener la fecha actual
                    Calendar c = Calendar.getInstance();
                    Calendar a = Calendar.getInstance();

                    // Aplicar la fecha
                    c.setTime(new Date());
                    a.setTime(new Date());
                    c.add(Calendar.DATE, 7); // Añadir la nueva fecha de entrega (1 semana apartir de la fecha actual)

                    // Guardar en una cadena de caracteres la fecha
                    String fechaEntrega = sdf.format(c.getTime());
                    String fechaActual = sdf.format(a.getTime());

                    respuesta = "\nBiblioteca renovando el prestamo con codigo " + codigo + " desde la sede "+ sede + "...\nLa fecha actual es: " + fechaActual + "\nLa nueva fecha de entrega es: " + fechaEntrega +"\n";

                    // Aceptar de forma inmediata la operacion y devolver una respusesta positva
                    System.out.println("Devolviendo respuesta al proceso solicitante...");
                    socket.send(respuesta.getBytes(ZMQ.CHARSET), 0);

                    // Publicar informacion del requerimiento
                    topico = "Renovacion";
                    publisher.send(topico + " " + codigo + " " + fechaActual + " " + fechaEntrega); // Se envia: topico, codigo, fecha actual, fecha nueva de entrega
                }
                else if(accion.equalsIgnoreCase("solicitar"))
                {
                    // Asignarle el trabajo al ActorSolicitar
                    socketSolicitar.send(solicitud.getBytes(ZMQ.CHARSET), 0);

                    // Se obtiene la respuesta del actorSolicitar
                    byte[] replySolicitar = socketSolicitar.recv(0);
                    System.out.println("Mensaje recibido del actor: " + new String(replySolicitar, ZMQ.CHARSET) + " desde la sede "+ sede);

                    // Enviar la respuesta al proceso solicitante
                    System.out.println("Devolviendo respuesta al proceso solicitante...");
                    System.out.println("////////////////////////////////////////////////////////////\n");
                    String respuestaSolicitante = new String(replySolicitar, ZMQ.CHARSET);
                    respuestaSolicitante = respuestaSolicitante + " desde la sede "+ sede +"\n";
                    socket.send(respuestaSolicitante.getBytes(ZMQ.CHARSET), 0); // Se envia la respuesta al proceso solicitante
                }
                else{
                    System.out.println("Operacion no soportada, las operaciones validas son: ");
                    System.out.println("devolver,<codigo del prestamo>,<numero de la sede>");
                    System.out.println("renovar,<codigo del prestamo>,<numero de la sede>");
                    System.out.println("solicitar,<codigo del libro>,<numero de la sede>");
                }

                 // Configurar el tiempo de espera
                Thread.sleep(1000); // Tiempo de espera para hacer el trabajo
            }

        } catch (InterruptedException e) {
            System.out.println("\nFalla del gestor: ");
            e.printStackTrace();

            socket.close();
            publisher.close();
            socketSolicitar.close();
            context.close();

        }
        catch (org.zeromq.ZMQException e) {
            System.err.println("\nFalla del gestor, excepción de ZeroMQ: " + e.getMessage());

            socket.close();
            publisher.close();
            socketSolicitar.close();
            context.close();
        }
    }

Try With Resources try(ZContext context=new ZContext()) in method public iniciar(gestor GC) : void from class com.ISD.ProcesoHomologo


    public void iniciarProcesoHomologo() {

         // Inicio el gestor
         try (ZContext context = new ZContext()){

            String respuesta;
            String topico;

            while (!Thread.currentThread().isInterrupted())
            {
                System.out.println("entre while ..... ");
                // Se recibe el mensaje del proceso solicitante
                byte[] reply = this.gestor.getSocket().recv(0);
                String solicitud = new String(reply, ZMQ.CHARSET); // Se genera un string con la solicitud con formato: accion, codigo

                System.out.println("llego la solicitud: " + solicitud);

                // Se guarda la informacion de la solicitud
                String[] elemSolicitud = solicitud.split(" ");
                String accion = elemSolicitud[0];
                int codigo = Integer.parseInt(elemSolicitud[1]);
                int sede = Integer.parseInt(elemSolicitud[2]);

                System.out.println("\n////////////////////////////////////////////////////////////");
                System.out.println("Mensaje del proceso solicitante: operacion - " + accion + ", codigo - " + codigo + ", sede - " + sede);

                // Dependiendo de la solicitud se realizara una accion
                if(accion.equalsIgnoreCase("devolver")){

                    respuesta = "\nBibilioteca recibiendo libro con codigo " + codigo + " desde la sede "+ sede + "...\n";

                    // Aceptar de forma inmediata la operacion y devolver una respusesta positva
                    System.out.println("Devolviendo respuesta al proceso solicitante...");
                    this.gestor.getSocket().send(respuesta.getBytes(ZMQ.CHARSET), 0);

                    // Publicar informacion del requerimiento
                    topico = "Devolucion";
                    this.gestor.getPublisher().send(topico + " " + codigo); //Se envia: topico, codigo
                }
                else if(accion.equalsIgnoreCase("renovar")){

                    // Configurar el formato de la fecha
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

                    // Obtener la fecha actual
                    Calendar c = Calendar.getInstance();
                    Calendar a = Calendar.getInstance();

                    // Aplicar la fecha
                    c.setTime(new Date());
                    a.setTime(new Date());
                    c.add(Calendar.DATE, 7); // Añadir la nueva fecha de entrega (1 semana apartir de la fecha actual)

                    // Guardar en una cadena de caracteres la fecha
                    String fechaEntrega = sdf.format(c.getTime());
                    String fechaActual = sdf.format(a.getTime());

                    respuesta = "\nBiblioteca renovando el prestamo con codigo " + codigo + " desde la sede "+ sede + "...\nLa fecha actual es: " + fechaActual + "\nLa nueva fecha de entrega es: " + fechaEntrega +"\n";

                    // Aceptar de forma inmediata la operacion y devolver una respusesta positva
                    System.out.println("Devolviendo respuesta al proceso solicitante...");
                    this.gestor.getSocket().send(respuesta.getBytes(ZMQ.CHARSET), 0);

                    // Publicar informacion del requerimiento
                    topico = "Renovacion";
                    this.gestor.getPublisher().send(topico + " " + codigo + " " + fechaActual + " " + fechaEntrega); // Se envia: topico, codigo, fecha actual, fecha nueva de entrega
                }
                else if(accion.equalsIgnoreCase("solicitar"))
                {
                    // Asignarle el trabajo al ActorSolicitar
                    this.gestor.getSocketSolicitar().send(solicitud.getBytes(ZMQ.CHARSET), 0);

                    // Se obtiene la respuesta del actorSolicitar
                    byte[] replySolicitar = this.gestor.getSocketSolicitar().recv(0);
                    System.out.println("Mensaje recibido del actor: " + new String(replySolicitar, ZMQ.CHARSET) + " desde la sede "+ sede);

                    // Enviar la respuesta al proceso solicitante
                    System.out.println("Devolviendo respuesta al proceso solicitante...");
                    System.out.println("////////////////////////////////////////////////////////////\n");
                    String respuestaSolicitante = new String(replySolicitar, ZMQ.CHARSET);
                    respuestaSolicitante = respuestaSolicitante + " desde la sede "+ sede +"\n";
                    this.gestor.getSocket().send(respuestaSolicitante.getBytes(ZMQ.CHARSET), 0); // Se envia la respuesta al proceso solicitante
                }
                else{
                    System.out.println("Operacion no soportada, las operaciones validas son: ");
                    System.out.println("devolver,<codigo del prestamo>,<numero de la sede>");
                    System.out.println("renovar,<codigo del prestamo>,<numero de la sede>");
                    System.out.println("solicitar,<codigo del libro>,<numero de la sede>");
                }

                 // Configurar el tiempo de espera
                Thread.sleep(1000); // Tiempo de espera para hacer el trabajo
            }

        } catch (InterruptedException e) {

            System.out.println();
            System.out.println("\nFalla del gestor: ");
            e.printStackTrace();
            System.out.println();

            this.gestor.getContext().close();
            this.gestor.getSocket().close();
            this.gestor.getPublisher().close();
            this.gestor.getSocketSolicitar().close();

        }
        catch (org.zeromq.ZMQException e) {

            System.out.println();
            System.err.println("\nFalla del gestor, excepción de ZeroMQ: " + e.getMessage());
            e.printStackTrace();
            System.out.println();

            this.gestor.getContext().close();
            this.gestor.getSocket().close();
            this.gestor.getPublisher().close();
            this.gestor.getSocketSolicitar().close();
        }
    }

    @Override
    public void run()
    {
        ZContext context = new ZContext();

        System.out.println("------------------INICIANDO GESTOR----------------");
        // Vincular con el puerto de los procesos solicitantes
        ZMQ.Socket socket = context.createSocket(SocketType.REP);
        // puerto de los procesos solicitantes
        // socket.bind("tcp://10.43.100.136:5555");
        //puerto local
        socket.bind("tcp://localhost:5555");

        // Vincular con un puerto para publicar los topicos
        ZMQ.Socket publisher = context.createSocket(SocketType.PUB);
        publisher.bind("tcp://localhost:5556");

        // Conexion con un puerto para la operacion de solicitar
        ZMQ.Socket socketSolicitar = context.createSocket(SocketType.REQ);
        socketSolicitar.connect("tcp://localhost:5557");

        // Inicio el gestor
        try {

            System.out.println("entre aqui");
            // Variables auxiliares para recibir valores
            String respuesta;
            String topico;

            while (!Thread.currentThread().isInterrupted())
            {
                System.out.println("entre while ..... ");
                // Se recibe el mensaje del proceso solicitante
                byte[] reply = socket.recv(0);
                String solicitud = new String(reply, ZMQ.CHARSET); // Se genera un string con la solicitud con formato: accion, codigo

                System.out.println("llego la solicitud: " + solicitud);

                // Se guarda la informacion de la solicitud
                String[] elemSolicitud = solicitud.split(" ");
                String accion = elemSolicitud[0];
                int codigo = Integer.parseInt(elemSolicitud[1]);
                int sede = Integer.parseInt(elemSolicitud[2]);

                System.out.println("\n////////////////////////////////////////////////////////////");
                System.out.println("Mensaje del proceso solicitante: operacion - " + accion + ", codigo - " + codigo + ", sede - " + sede);

                // Dependiendo de la solicitud se realizara una accion
                if(accion.equalsIgnoreCase("devolver")){

                    respuesta = "\nBibilioteca recibiendo libro con codigo " + codigo + " desde la sede "+ sede + "...\n";

                    // Aceptar de forma inmediata la operacion y devolver una respusesta positva
                    System.out.println("Devolviendo respuesta al proceso solicitante...");
                    socket.send(respuesta.getBytes(ZMQ.CHARSET), 0);

                    // Publicar informacion del requerimiento
                    topico = "Devolucion";
                    publisher.send(topico + " " + codigo); //Se envia: topico, codigo
                }
                else if(accion.equalsIgnoreCase("renovar")){

                    // Configurar el formato de la fecha
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

                    // Obtener la fecha actual
                    Calendar c = Calendar.getInstance();
                    Calendar a = Calendar.getInstance();

                    // Aplicar la fecha
                    c.setTime(new Date());
                    a.setTime(new Date());
                    c.add(Calendar.DATE, 7); // Añadir la nueva fecha de entrega (1 semana apartir de la fecha actual)

                    // Guardar en una cadena de caracteres la fecha
                    String fechaEntrega = sdf.format(c.getTime());
                    String fechaActual = sdf.format(a.getTime());

                    respuesta = "\nBiblioteca renovando el prestamo con codigo " + codigo + " desde la sede "+ sede + "...\nLa fecha actual es: " + fechaActual + "\nLa nueva fecha de entrega es: " + fechaEntrega +"\n";

                    // Aceptar de forma inmediata la operacion y devolver una respusesta positva
                    System.out.println("Devolviendo respuesta al proceso solicitante...");
                    socket.send(respuesta.getBytes(ZMQ.CHARSET), 0);

                    // Publicar informacion del requerimiento
                    topico = "Renovacion";
                    publisher.send(topico + " " + codigo + " " + fechaActual + " " + fechaEntrega); // Se envia: topico, codigo, fecha actual, fecha nueva de entrega
                }
                else if(accion.equalsIgnoreCase("solicitar"))
                {
                    // Asignarle el trabajo al ActorSolicitar
                    socketSolicitar.send(solicitud.getBytes(ZMQ.CHARSET), 0);

                    // Se obtiene la respuesta del actorSolicitar
                    byte[] replySolicitar = socketSolicitar.recv(0);
                    System.out.println("Mensaje recibido del actor: " + new String(replySolicitar, ZMQ.CHARSET) + " desde la sede "+ sede);

                    // Enviar la respuesta al proceso solicitante
                    System.out.println("Devolviendo respuesta al proceso solicitante...");
                    System.out.println("////////////////////////////////////////////////////////////\n");
                    String respuestaSolicitante = new String(replySolicitar, ZMQ.CHARSET);
                    respuestaSolicitante = respuestaSolicitante + " desde la sede "+ sede +"\n";
                    socket.send(respuestaSolicitante.getBytes(ZMQ.CHARSET), 0); // Se envia la respuesta al proceso solicitante
                }
                else{
                    System.out.println("Operacion no soportada, las operaciones validas son: ");
                    System.out.println("devolver,<codigo del prestamo>,<numero de la sede>");
                    System.out.println("renovar,<codigo del prestamo>,<numero de la sede>");
                    System.out.println("solicitar,<codigo del libro>,<numero de la sede>");
                }

                 // Configurar el tiempo de espera
                Thread.sleep(1000); // Tiempo de espera para hacer el trabajo
            }

        } catch (InterruptedException e) {
            System.out.println("\nFalla del gestor: ");
            e.printStackTrace();

            socket.close();
            publisher.close();
            socketSolicitar.close();
            context.close();

            procesoHomologo();
        }
        catch (org.zeromq.ZMQException e) {
            System.err.println("\nFalla del gestor, excepción de ZeroMQ: " + e.getMessage());

            socket.close();
            publisher.close();
            socketSolicitar.close();
            context.close();

            procesoHomologo();
        }
    }

Try With Resources try(ZContext context=new ZContext()) in method public iniciarProcesoHomologo() : void from class com.ISD.ProcesoHomologo


    /**
     * Generates the image for the now playing
     *
     * @param res
     * @return
     */
    @SparkGet
    public Object nowPlaying(@SparkQueryParam("width") Integer width, @SparkQueryParam("height") Integer height, @SparkQueryParam("scale") Double scale, Response res) throws Exception {

        Dimension dimension = FULL_HD;
        if (width != null && height != null) {
            dimension = new Dimension(width, height);
        }

        scale = Optional.ofNullable(scale).orElse(1D);
        logger.info("Getting now playing for dimension:{} and scale {}", dimension, scale);
        BufferedImage toUse;

        Pair<Dimension, Double> cacheEntry = new Pair<>(dimension, scale);
        if (imageCache.containsKey(cacheEntry)) {
            Pair<LocalDateTime, BufferedImage> localDateTimePathPair = imageCache.get(cacheEntry);
            long timeDiff = Math.abs(ChronoUnit.SECONDS.between(localDateTimePathPair.getKey(), LocalDateTime.now()));
            logger.info("Time diff with cache = {}", timeDiff);
            if (timeDiff <= 5) {
                logger.info("Using cache instead");
                toUse = localDateTimePathPair.getValue();
            } else {
                toUse = getContent(dimension, scale);
            }

        } else {
            toUse = getContent(dimension, scale);
        }

        res.raw().setContentType("application/octet-stream");
        res.raw().setHeader("Content-Disposition", "inline; filename=now-playing-" + dimension.width + "x" + dimension.height + "x" + scale + ".png");

        try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
            ImageIO.write(toUse, "png", os);
            res.raw().getOutputStream().write(os.toByteArray());

            return res.raw();

        } finally {
        }

    }

    /**
     * Generates the image for the now playing
     *
     * @param res
     * @return
     */
    @SparkGet
    public Object nowPlaying(@SparkQueryParam("width") Integer width, @SparkQueryParam("height") Integer height, @SparkQueryParam("scale") Double scale, Response res) throws Exception {

        Dimension dimension = FULL_HD;
        if (width != null && height != null) {
            dimension = new Dimension(width, height);
        }

        scale = Optional.ofNullable(scale).orElse(1D);
        logger.info("Getting now playing for dimension:{} and scale {}", dimension, scale);
        Path toUse;

        Pair<Dimension, Double> cacheEntry = new Pair<>(dimension, scale);
        if (imageCache.containsKey(cacheEntry)) {
            Pair<LocalDateTime, Path> localDateTimePathPair = imageCache.get(cacheEntry);
            long timeDiff = Math.abs(ChronoUnit.SECONDS.between(localDateTimePathPair.getKey(), LocalDateTime.now()));
            logger.info("Time diff with cache = {}", timeDiff);
            if (timeDiff <= 5) {
                logger.info("Using cache instead");
                toUse = localDateTimePathPair.getValue();
            } else {
                toUse = getContent(dimension, scale);
            }

        } else {
            toUse = getContent(dimension, scale);
        }

        res.raw().setContentType("application/octet-stream");
        res.raw().setHeader("Content-Disposition", "inline; filename=now-playing-" + dimension.width + "x" + dimension.height + "x"+scale+".png");

        InputStream in = new FileInputStream(toUse.toFile());

        try {
            byte[] buffer = new byte[1024];
            int len;
            while ((len = in.read(buffer)) > 0) {
                res.raw().getOutputStream().write(buffer, 0, len);
            }

            return res.raw();

        } finally {
            in.close();
        }

    }

Try With Resources try(ByteArrayOutputStream os=new ByteArrayOutputStream()) in method public nowPlaying(width Integer, height Integer, scale Double, res Response) : Object from class com.ftpix.nowplaying.controllers.NowPlayingController


	@Before
	public void prepare() {
		index = new TriePrefixIndex<>(identity());
		result = null;
		expected = null;
	}

	@Before
	public void prepare() {
		index = new TriePrefixIndex<String>(identity());
		result = null;
		expected = null;
	}

Replace Generic With Diamond TriePrefixIndex<String> with TriePrefixIndex<> in method public prepare() : void from class com.illucit.instatrie.TestHighlighting


	@Override
	public Uid create(String resourceEndPoint, ObjectTranslator objectTranslator, Set<Attribute> attributes,
			Set<Attribute> injectedAttributeSet, ScimConnectorConfiguration conf) {

		Header authHeader = null;
		String scimBaseUri = "";
		Map<String, Object> authorizationData = ServiceAccessManager.logIntoService(conf);

		for (String data : authorizationData.keySet()) {
			if (AUTHHEADER.equals(data)) {

				authHeader = (Header) authorizationData.get(data);

			} else if (URI.equals(data)) {

				scimBaseUri = (String) authorizationData.get(data);
			}
		}

		if (authHeader == null || scimBaseUri.isEmpty()) {

			throw new ConnectorException("The data needed for authorization of request to the provider was not found.");
		}

		injectedAttributeSet = attributeInjection(injectedAttributeSet, authorizationData);

		JSONObject jsonObject = new JSONObject();

		jsonObject = objectTranslator.translateSetToJson(attributes, injectedAttributeSet, resourceEndPoint);

		HttpClientBuilder httpClientBulder = HttpClientBuilder.create();

		if (StringUtil.isNotEmpty(conf.getProxyUrl())) {
			HttpHost proxy = new HttpHost(conf.getProxyUrl(), conf.getProxyPortNumber());
			DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
			httpClientBulder.setRoutePlanner(routePlanner);
		}

		HttpClient httpClient = httpClientBulder.build();

		String uri = new StringBuilder(scimBaseUri).append(SLASH).append(resourceEndPoint).append(SLASH).toString();

		LOGGER.info("Query url: {0}", uri);

		try {
			// LOGGER.info("Json object to be send: {0}",
			// jsonObject.toString(1));

			HttpPost httpPost = buildHttpPost(uri, authHeader, jsonObject);
			String responseString = null;
			try (CloseableHttpResponse response = (CloseableHttpResponse) httpClient.execute(httpPost)) {

				HttpEntity entity = response.getEntity();

				if (entity != null) {
					responseString = EntityUtils.toString(entity);
				} else {
					responseString = "";
				}

				int statusCode = response.getStatusLine().getStatusCode();
				LOGGER.info("Status code: {0}", statusCode);

				if (statusCode == 201) {
					// LOGGER.info("Creation of resource was successful");

					if (!responseString.isEmpty()) {
						JSONObject json = new JSONObject(responseString);

						Uid uid = new Uid(json.getString(ID));

						// LOGGER.info("Json response: {0}", json.toString(1));
						return uid;
					} else {
						return null;
					}
				} else {
					handleInvalidStatus(" while resource creation, please check if credentials are valid. ",
							responseString, "creating a new object", statusCode);
				}

			} catch (ClientProtocolException e) {
				LOGGER.error(
						"An protocol exception has occurred while in the process of creating a new resource object. Possible mismatch in interpretation of the HTTP specification: {0}",
						e.getLocalizedMessage());
				LOGGER.info(
						"An protocol exception has occurred while in the process of creating a new resource object. Possible mismatch in interpretation of the HTTP specification: {0}",
						e);
				throw new ConnectionFailedException(
						"An protocol exception has occurred while in the process of creating a new resource object. Possible mismatch in interpretation of the HTTP specification: {0}",
						e);

			} catch (IOException e) {

				if ((e instanceof SocketTimeoutException || e instanceof NoRouteToHostException)) {

					throw new OperationTimeoutException(
							"The connection timed out. Occurrence in the process of creating a new resource object", e);
				} else {

					LOGGER.error(
							"An error has occurred while processing the http response. Occurrence in the process of creating a new resource object: {0}",
							e.getLocalizedMessage());
					LOGGER.info(
							"An error has occurred while processing the http response. Occurrence in the process of creating a new resource object: {0}",
							e);

					throw new ConnectorIOException(
							"An error has occurred while processing the http response. Occurrence in the process of creating a new resource object",
							e);
				}
			}

		} catch (JSONException e) {

			LOGGER.error(
					"An exception has occurred while processing an json object. Occurrence in the process of creating a new resource object: {0}",
					e.getLocalizedMessage());
			LOGGER.info(
					"An exception has occurred while processing an json object. Occurrence in the process of creating a new resource object: {0}",
					e);

			throw new ConnectorException(
					"An exception has occurred while processing an json object. Occurrence in the process of creating a new resource objec",
					e);
		} catch (UnsupportedEncodingException e) {
			LOGGER.error("Unsupported encoding: {0}. Occurrence in the process of creating a new resource object ",
					e.getLocalizedMessage());
			LOGGER.info("Unsupported encoding: {0}. Occurrence in the process of creating a new resource object ", e);

			throw new ConnectorException(
					"Unsupported encoding, Occurrence in the process of creating a new resource object ", e);
		}
		return null;
	}

	@Override
	public Uid create(String resourceEndPoint, ObjectTranslator objectTranslator, Set<Attribute> attributes,
			Set<Attribute> injectedAttributeSet, ScimConnectorConfiguration conf) {

		Header authHeader = null;
		String scimBaseUri = "";
		Map<String, Object> authorizationData = ServiceAccessManager.logIntoService(conf);

		for (String data : authorizationData.keySet()) {
			if (AUTHHEADER.equals(data)) {

				authHeader = (Header) authorizationData.get(data);

			} else if (URI.equals(data)) {

				scimBaseUri = (String) authorizationData.get(data);
			}
		}

		if (authHeader == null || scimBaseUri.isEmpty()) {

			throw new ConnectorException("The data needed for authorization of request to the provider was not found.");
		}

		injectedAttributeSet = attributeInjection(injectedAttributeSet, authorizationData);

		JSONObject jsonObject = new JSONObject();

		jsonObject = objectTranslator.translateSetToJson(attributes, injectedAttributeSet, resourceEndPoint);

		HttpClientBuilder httpClientBulder = HttpClientBuilder.create();

		if (StringUtil.isNotEmpty(conf.getProxyUrl())) {
			HttpHost proxy = new HttpHost(conf.getProxyUrl(), conf.getProxyPortNumber());
			DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
			httpClientBulder.setRoutePlanner(routePlanner);
		}

		HttpClient httpClient = httpClientBulder.build();
		CloseableHttpResponse response = null;
		String uri = new StringBuilder(scimBaseUri).append(SLASH).append(resourceEndPoint).append(SLASH).toString();

		LOGGER.info("Query url: {0}", uri);

		try {
			// LOGGER.info("Json object to be send: {0}",
			// jsonObject.toString(1));

			HttpPost httpPost = new HttpPost(uri);
			httpPost.addHeader(authHeader);
			httpPost.addHeader(PRETTYPRINTHEADER);

			StringEntity bodyContent = new StringEntity(jsonObject.toString(1));

			bodyContent.setContentType(CONTENTTYPE);
			httpPost.setEntity(bodyContent);
			String responseString = null;
			try {

				response = (CloseableHttpResponse) httpClient.execute(httpPost);
				responseString = EntityUtils.toString(response.getEntity());
				int statusCode = response.getStatusLine().getStatusCode();
				LOGGER.info("Status code: {0}", statusCode);
				if (statusCode == 201) {
					// LOGGER.info("Creation of resource was successful");

					JSONObject json = new JSONObject(responseString);

					Uid uid = new Uid(json.getString(ID));

					// LOGGER.info("Json response: {0}", json.toString(1));
					return uid;
				} else if (statusCode == 401){

					String error = ErrorHandler.onNoSuccess(responseString, statusCode, "creating a new object");
					StringBuilder errorString = new StringBuilder(
							"Unauthorized while resource creation, please check if credentials are valid. ").append(error);
					throw new InvalidCredentialException(errorString.toString());

				} else if (statusCode == 409) {

					String error = ErrorHandler.onNoSuccess(responseString, statusCode, "creating a new object");
					StringBuilder errorString = new StringBuilder(
							"Conflict while resource creation, resource evaluated as already created. ").append(error);
					throw new AlreadyExistsException(errorString.toString());
				} else {
					ErrorHandler.onNoSuccess(responseString, statusCode, "creating a new object");
				}

			} catch (ClientProtocolException e) {
				LOGGER.error(
						"An protocol exception has occurred while in the process of creating a new resource object. Possible mismatch in interpretation of the HTTP specification: {0}",
						e.getLocalizedMessage());
				LOGGER.info(
						"An protocol exception has occurred while in the process of creating a new resource object. Possible mismatch in interpretation of the HTTP specification: {0}",
						e);
				throw new ConnectionFailedException(
						"An protocol exception has occurred while in the process of creating a new resource object. Possible mismatch in interpretation of the HTTP specification: {0}",
						e);

			} catch (IOException e) {

				if ((e instanceof SocketTimeoutException || e instanceof NoRouteToHostException)) {

					throw new OperationTimeoutException(
							"The connection timed out. Occurrence in the process of creating a new resource object", e);
				} else {

					LOGGER.error(
							"An error has occurred while processing the http response. Occurrence in the process of creating a new resource object: {0}",
							e.getLocalizedMessage());
					LOGGER.info(
							"An error has occurred while processing the http response. Occurrence in the process of creating a new resource object: {0}",
							e);

					throw new ConnectorIOException(
							"An error has occurred while processing the http response. Occurrence in the process of creating a new resource object",
							e);
				}
			}

		} catch (JSONException e) {

			LOGGER.error(
					"An exception has occurred while processing an json object. Occurrence in the process of creating a new resource object: {0}",
					e.getLocalizedMessage());
			LOGGER.info(
					"An exception has occurred while processing an json object. Occurrence in the process of creating a new resource object: {0}",
					e);

			throw new ConnectorException(
					"An exception has occurred while processing an json object. Occurrence in the process of creating a new resource objec",
					e);
		} catch (UnsupportedEncodingException e) {
			LOGGER.error("Unsupported encoding: {0}. Occurrence in the process of creating a new resource object ",
					e.getLocalizedMessage());
			LOGGER.info("Unsupported encoding: {0}. Occurrence in the process of creating a new resource object ", e);

			throw new ConnectorException(
					"Unsupported encoding, Occurrence in the process of creating a new resource object ", e);
		} finally {
			try {
				response.close();
			} catch (IOException e) {

				if ((e instanceof SocketTimeoutException || e instanceof NoRouteToHostException)) {

					throw new OperationTimeoutException(
							"The connection timed out while closing the http connection. Occurrence in the process of creating a new resource object",
							e);
				} else {

					LOGGER.error(
							"An error has occurred while processing the http response and closing the http connection. Occurrence in the process of creating a new resource object: {0}",
							e.getLocalizedMessage());

					throw new ConnectorIOException(
							"An error has occurred while processing the http response and closing the http connection. Occurrence in the process of creating a new resource object",
							e);
				}

			}
		}
		return null;
	}

Try With Resources try(CloseableHttpResponse response=(CloseableHttpResponse)httpClient.execute(httpPost)) in method public create(resourceEndPoint String, objectTranslator ObjectTranslator, attributes Set<Attribute>, injectedAttributeSet Set<Attribute>, conf ScimConnectorConfiguration) : Uid from class com.evolveum.polygon.scim.StandardScimHandlingStrategy


	@Override
	public void query(Filter query, StringBuilder queryUriSnippet, String resourceEndPoint,
			ResultsHandler resultHandler, ScimConnectorConfiguration conf) {

		LOGGER.info("Processing query");

		Boolean isCAVGroupQuery = false; // is the query a ContainsAllValues
											// filter query for the group
											// endpoint?
		Boolean valueIsUid = false;

		Header authHeader = null;
		String scimBaseUri = "";
		Map<String, Object> authorizationData = ServiceAccessManager.logIntoService(conf);

		for (String data : authorizationData.keySet()) {
			if (AUTHHEADER.equals(data)) {

				authHeader = (Header) authorizationData.get(data);

			} else if (URI.equals(data)) {

				scimBaseUri = (String) authorizationData.get(data);
			}
		}

		if (authHeader == null || scimBaseUri.isEmpty()) {

			throw new ConnectorException("The data needed for authorization of request to the provider was not found.");
		}

		String q;

		String[] baseUrlParts = scimBaseUri.split("\\.");
		String providerName = baseUrlParts[1];

		if (query != null) {

			if (query instanceof EqualsFilter) {
				Attribute filterAttr = ((EqualsFilter) query).getAttribute();

				if (filterAttr instanceof Uid) {

					valueIsUid = true;

					isCAVGroupQuery = checkFilter(query, resourceEndPoint);

					if (!isCAVGroupQuery) {
						q = ((Uid) filterAttr).getUidValue();
					} else {
						q = ((Uid) filterAttr).getUidValue();
						resourceEndPoint = "Users";
					}
				} else {

					isCAVGroupQuery = checkFilter(query, resourceEndPoint);

					if (!isCAVGroupQuery) {
						LOGGER.info("Attribute not instance of UID");
						q = qIsFilter(query, queryUriSnippet, providerName, resourceEndPoint);
					} else {
						q = (String) filterAttr.getValue().get(0);
						resourceEndPoint = "Users";
					}

				}

			} else {

				isCAVGroupQuery = checkFilter(query, resourceEndPoint);

				if (!isCAVGroupQuery) {
					q = qIsFilter(query, queryUriSnippet, providerName, resourceEndPoint);
				} else {

					Attribute filterAttr = ((AttributeFilter) query).getAttribute();
					q = (String) filterAttr.getValue().get(0);
					resourceEndPoint = "Users";
				}
			}

		} else {
			LOGGER.info("No filter was defined, query will return all the resource values");
			q = queryUriSnippet.toString();

		}

		HttpClientBuilder httpClientBulder = HttpClientBuilder.create();

		if (StringUtil.isNotEmpty(conf.getProxyUrl())) {
			HttpHost proxy = new HttpHost(conf.getProxyUrl(), conf.getProxyPortNumber());
			DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
			httpClientBulder.setRoutePlanner(routePlanner);
		}

		HttpClient httpClient = httpClientBulder.build();

		String uri = new StringBuilder(scimBaseUri).append(SLASH).append(resourceEndPoint).append(SLASH).append(q)
				.toString();
		LOGGER.info("Qeury url: {0}", uri);
		HttpGet httpGet = buildHttpGet(uri, authHeader);
		String responseString = null;
		try (CloseableHttpResponse response = (CloseableHttpResponse) httpClient.execute(httpGet)) {
			int statusCode = response.getStatusLine().getStatusCode();
			HttpEntity entity = response.getEntity();

			if (entity != null) {
				responseString = EntityUtils.toString(entity);
			} else {
				responseString = "";
			}
			LOGGER.info("Status code: {0}", statusCode);
			if (statusCode == 200) {

				if (!responseString.isEmpty()) {
					try {
						JSONObject jsonObject = new JSONObject(responseString);

						//LOGGER.info("Json object returned from service provider: {0}", jsonObject.toString(1));
						try {

							if (valueIsUid) {

								ConnectorObject connectorObject = buildConnectorObject(jsonObject, resourceEndPoint);
								resultHandler.handle(connectorObject);

							} else {

								if (isCAVGroupQuery) {

									handleCAVGroupQuery(jsonObject, GROUPS, resultHandler, scimBaseUri, authHeader);

								} else if (jsonObject.has(RESOURCES)) {
									int amountOfResources = jsonObject.getJSONArray(RESOURCES).length();
									int totalResults = 0;
									int startIndex = 0;
									int itemsPerPage = 0;

									if (jsonObject.has(STARTINDEX) && jsonObject.has(TOTALRESULTS)
											&& jsonObject.has(ITEMSPERPAGE)) {
										totalResults = (int) jsonObject.get(TOTALRESULTS);
										startIndex = (int) jsonObject.get(STARTINDEX);
										itemsPerPage = (int) jsonObject.get(ITEMSPERPAGE);
									}

									for (int i = 0; i < amountOfResources; i++) {
										JSONObject minResourceJson = new JSONObject();
										minResourceJson = jsonObject.getJSONArray(RESOURCES).getJSONObject(i);
										if (minResourceJson.has(ID) && minResourceJson.getString(ID) != null) {

											if (minResourceJson.has(USERNAME)){

												ConnectorObject connectorObject = buildConnectorObject(
														minResourceJson, resourceEndPoint);

												resultHandler.handle(connectorObject);
											}else if(!USERS.equals(resourceEndPoint)){

												if(minResourceJson.has(DISPLAYNAME)){
													ConnectorObject connectorObject = buildConnectorObject(
															minResourceJson, resourceEndPoint);
													resultHandler.handle(connectorObject);
												}
											}else if (minResourceJson.has(META)) {

												String resourceUri = minResourceJson.getJSONObject(META)
														.getString("location").toString();

												HttpGet httpGetR = buildHttpGet(resourceUri, authHeader);
												try (CloseableHttpResponse resourceResponse = (CloseableHttpResponse) httpClient
														.execute(httpGetR)) {

													statusCode = resourceResponse.getStatusLine().getStatusCode();
													responseString = EntityUtils.toString(resourceResponse.getEntity());
													if (statusCode == 200) {

														JSONObject fullResourcejson = new JSONObject(responseString);

														// LOGGER.info(
														// "The {0}. resource
														// jsonobject which was
														// returned by the
														// service
														// provider: {1}",
														// i + 1,
														// fullResourcejson);

														ConnectorObject connectorObject = buildConnectorObject(
																fullResourcejson, resourceEndPoint);

														resultHandler.handle(connectorObject);

													} else {

														ErrorHandler.onNoSuccess(responseString, statusCode,
																resourceUri);

													}
												}
											}
										} else {
											LOGGER.error("No uid present in fetched object: {0}", minResourceJson);

											throw new ConnectorException(
													"No uid present in fetchet object while processing queuery result");

										}
									}
									if (resultHandler instanceof SearchResultsHandler) {
										Boolean allResultsReturned = false;
										int remainingResult = totalResults - (startIndex - 1) - itemsPerPage;

										if (remainingResult <= 0) {
											remainingResult = 0;
											allResultsReturned = true;

										}

										// LOGGER.info("The number of remaining
										// results: {0}", remainingResult);
										SearchResult searchResult = new SearchResult(DEFAULT, remainingResult,
												allResultsReturned);
										((SearchResultsHandler) resultHandler).handleResult(searchResult);
									}

								} else {

									LOGGER.error("Resource object not present in provider response to the query");

									throw new ConnectorException(
											"No uid present in fetchet object while processing queuery result");

								}
							}

						} catch (Exception e) {
							LOGGER.error(
									"Builder error. Error while building connId object. The exception message: {0}",
									e.getLocalizedMessage());
							LOGGER.info("Builder error. Error while building connId object. The excetion message: {0}",
									e);
							throw new ConnectorException("Builder error. Error while building connId object.", e);
						}

					} catch (JSONException jsonException) {
						if (q == null) {
							q = "the full resource representation";
						}
						LOGGER.error(
								"An exception has occurred while setting the variable \"jsonObject\". Occurrence while processing the http response to the queuey request for: {1}, exception message: {0}",
								jsonException.getLocalizedMessage(), q);
						LOGGER.info(
								"An exception has occurred while setting the variable \"jsonObject\". Occurrence while processing the http response to the queuey request for: {1}, exception message: {0}",
								jsonException, q);
						throw new ConnectorException(
								"An exception has occurred while setting the variable \"jsonObject\".", jsonException);
					}

				} else {

					LOGGER.warn("Service provider response is empty, responce returned on query: {0}", q);
				}
			} else if (statusCode == 401) {

				handleInvalidStatus("while querying for resources. ", responseString, "retrieving an object",
						statusCode);

			} else if (valueIsUid) {
				ErrorHandler.onNoSuccess(responseString, statusCode, uri);

				StringBuilder errorBuilder = new StringBuilder("The resource with the uid: ").append(q)
						.append(" was not found.");

				throw new ConnectorException(errorBuilder.toString());
			} else {
				ErrorHandler.onNoSuccess(responseString, statusCode, uri);
			}

		} catch (IOException e) {

			if (q == null) {
				q = "the full resource representation";
			}

			StringBuilder errorBuilder = new StringBuilder(
					"An error occurred while processing the query http response for ");
			errorBuilder.append(q);
			if ((e instanceof SocketTimeoutException || e instanceof NoRouteToHostException)) {

				errorBuilder.insert(0, "The connection timed out while closing the http connection. ");

				throw new OperationTimeoutException(errorBuilder.toString(), e);
			} else {

				LOGGER.error(
						"An error occurred while processing the queuery http response. Occurrence while processing the http response to the queuey request for: {1}, exception message: {0}",
						e.getLocalizedMessage(), q);
				LOGGER.info(
						"An error occurred while processing the queuery http response. Occurrence while processing the http response to the queuey request for: {1}, exception message: {0}",
						e, q);
				throw new ConnectorIOException(errorBuilder.toString(), e);
			}
		}
	}

	@Override
	public void query(Filter query, StringBuilder queryUriSnippet, String resourceEndPoint,
			ResultsHandler resultHandler, ScimConnectorConfiguration conf) {

		LOGGER.info("Processing query");

		Boolean isCAVGroupQuery = false; // is the query a ContainsAllValues
											// filter query for the group
											// endpoint?
		Boolean valueIsUid = false;

		Header authHeader = null;
		String scimBaseUri = "";
		Map<String, Object> authorizationData = ServiceAccessManager.logIntoService(conf);

		for (String data : authorizationData.keySet()) {
			if (AUTHHEADER.equals(data)) {

				authHeader = (Header) authorizationData.get(data);

			} else if (URI.equals(data)) {

				scimBaseUri = (String) authorizationData.get(data);
			}
		}

		if (authHeader == null || scimBaseUri.isEmpty()) {

			throw new ConnectorException("The data needed for authorization of request to the provider was not found.");
		}

		String q;

		String[] baseUrlParts = scimBaseUri.split("\\.");
		String providerName = baseUrlParts[1];

		if (query != null) {

			if (query instanceof EqualsFilter) {
				Attribute filterAttr = ((EqualsFilter) query).getAttribute();

				if (filterAttr instanceof Uid) {

					valueIsUid = true;

					isCAVGroupQuery = checkFilter(query, resourceEndPoint);

					if (!isCAVGroupQuery) {
						q = ((Uid) filterAttr).getUidValue();
					} else {
						q = ((Uid) filterAttr).getUidValue();
						resourceEndPoint = "Users";
					}
				} else {

					isCAVGroupQuery = checkFilter(query, resourceEndPoint);

					if (!isCAVGroupQuery) {
						LOGGER.info("Attribute not instance of UID");
						q = qIsFilter(query, queryUriSnippet, providerName, resourceEndPoint);
					} else {
						q = (String) filterAttr.getValue().get(0);
						resourceEndPoint = "Users";
					}

				}

			} else {

				isCAVGroupQuery = checkFilter(query, resourceEndPoint);

				if (!isCAVGroupQuery) {
					q = qIsFilter(query, queryUriSnippet, providerName, resourceEndPoint);
				} else {

					Attribute filterAttr = ((AttributeFilter) query).getAttribute();
					q = (String) filterAttr.getValue().get(0);
					resourceEndPoint = "Users";
				}
			}

		} else {
			LOGGER.info("No filter was defined, query will return all the resource values");
			q = queryUriSnippet.toString();

		}

		HttpClientBuilder httpClientBulder = HttpClientBuilder.create();

		if (StringUtil.isNotEmpty(conf.getProxyUrl())) {
			HttpHost proxy = new HttpHost(conf.getProxyUrl(), conf.getProxyPortNumber());
			DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
			httpClientBulder.setRoutePlanner(routePlanner);
		}

		HttpClient httpClient = httpClientBulder.build();

		String uri = new StringBuilder(scimBaseUri).append(SLASH).append(resourceEndPoint).append(SLASH).append(q)
				.toString();
		LOGGER.info("Qeury url: {0}", uri);
		HttpGet httpGet = new HttpGet(uri);
		httpGet.addHeader(authHeader);
		httpGet.addHeader(PRETTYPRINTHEADER);

		String responseString = null;
		CloseableHttpResponse response = null;
		try {
			response = (CloseableHttpResponse) httpClient.execute(httpGet);

			int statusCode = response.getStatusLine().getStatusCode();
			responseString = EntityUtils.toString(response.getEntity());
			LOGGER.info("Status code: {0}", statusCode);
			if (statusCode == 200) {

				if (!responseString.isEmpty()) {
					try {
						JSONObject jsonObject = new JSONObject(responseString);

						LOGGER.info("Json object returned from service provider: {0}", jsonObject.toString(1));
						try {

							if (valueIsUid) {

								ConnectorObject connectorObject = buildConnectorObject(jsonObject, resourceEndPoint);
								resultHandler.handle(connectorObject);

							} else {

								if (isCAVGroupQuery) {

									handleCAVGroupQuery(jsonObject, GROUPS, resultHandler, scimBaseUri, authHeader);

								} else if (jsonObject.has(RESOURCES)) {
									int amountOfResources = jsonObject.getJSONArray(RESOURCES).length();
									int totalResults = 0;
									int startIndex = 0;
									int itemsPerPage = 0;

									if (jsonObject.has(STARTINDEX) && jsonObject.has(TOTALRESULTS)
											&& jsonObject.has(ITEMSPERPAGE)) {
										totalResults = (int) jsonObject.get(TOTALRESULTS);
										startIndex = (int) jsonObject.get(STARTINDEX);
										itemsPerPage = (int) jsonObject.get(ITEMSPERPAGE);
									}

									for (int i = 0; i < amountOfResources; i++) {
										JSONObject minResourceJson = new JSONObject();
										minResourceJson = jsonObject.getJSONArray(RESOURCES).getJSONObject(i);
										if (minResourceJson.has(ID) && minResourceJson.getString(ID) != null) {

											if (minResourceJson.has(META)) {

												String resourceUri = minResourceJson.getJSONObject(META)
														.getString("location").toString();
												HttpGet httpGetR = new HttpGet(resourceUri);
												httpGetR.addHeader(authHeader);
												httpGetR.addHeader(PRETTYPRINTHEADER);

												CloseableHttpResponse resourceResponse = (CloseableHttpResponse) httpClient
														.execute(httpGetR);

												statusCode = resourceResponse.getStatusLine().getStatusCode();
												responseString = EntityUtils.toString(resourceResponse.getEntity());
												if (statusCode == 200) {

													JSONObject fullResourcejson = new JSONObject(responseString);

													// LOGGER.info(
													// "The {0}. resource
													// jsonobject which was
													// returned by the service
													// provider: {1}",
													// i + 1, fullResourcejson);

													ConnectorObject connectorObject = buildConnectorObject(
															fullResourcejson, resourceEndPoint);

													resultHandler.handle(connectorObject);

												} else {

													ErrorHandler.onNoSuccess(responseString, statusCode, resourceUri);

												}
												resourceResponse.close();
											}
										} else {
											LOGGER.error("No uid present in fetched object: {0}", minResourceJson);

											throw new ConnectorException(
													"No uid present in fetchet object while processing queuery result");

										}
									}
									if (resultHandler instanceof SearchResultsHandler) {
										Boolean allResultsReturned = false;
										int remainingResult = totalResults - (startIndex - 1) - itemsPerPage;

										if (remainingResult <= 0) {
											remainingResult = 0;
											allResultsReturned = true;

										}

										// LOGGER.info("The number of remaining
										// results: {0}", remainingResult);
										SearchResult searchResult = new SearchResult(DEFAULT, remainingResult,
												allResultsReturned);
										((SearchResultsHandler) resultHandler).handleResult(searchResult);
									}

								} else {

									LOGGER.error("Resource object not present in provider response to the query");

									throw new ConnectorException(
											"No uid present in fetchet object while processing queuery result");

								}
							}

						} catch (Exception e) {
							LOGGER.error(
									"Builder error. Error while building connId object. The exception message: {0}",
									e.getLocalizedMessage());
							LOGGER.info("Builder error. Error while building connId object. The excetion message: {0}",
									e);
							throw new ConnectorException("Builder error. Error while building connId object.", e);
						}

					} catch (JSONException jsonException) {
						if (q == null) {
							q = "the full resource representation";
						}
						LOGGER.error(
								"An exception has occurred while setting the variable \"jsonObject\". Occurrence while processing the http response to the queuey request for: {1}, exception message: {0}",
								jsonException.getLocalizedMessage(), q);
						LOGGER.info(
								"An exception has occurred while setting the variable \"jsonObject\". Occurrence while processing the http response to the queuey request for: {1}, exception message: {0}",
								jsonException, q);
						throw new ConnectorException(
								"An exception has occurred while setting the variable \"jsonObject\".", jsonException);
					}

				} else {

					LOGGER.warn("Service provider response is empty, responce returned on query: {0}", q);
				}
			}else if (statusCode == 401){

				String error = ErrorHandler.onNoSuccess(responseString, statusCode, "retrieving an object");
				StringBuilder errorString = new StringBuilder(
						"Unauthorized while querying for resources, please check if credentials are valid. ").append(error);
				throw new InvalidCredentialException(errorString.toString());

			} else if (valueIsUid) {
				ErrorHandler.onNoSuccess(responseString, statusCode, uri);

				StringBuilder errorBuilder = new StringBuilder("The resource with the uid: ").append(q)
						.append(" was not found.");

				throw new ConnectorException(errorBuilder.toString());
			} else {
				ErrorHandler.onNoSuccess(responseString, statusCode, uri);
			}

		} catch (IOException e) {

			if (q == null) {
				q = "the full resource representation";
			}

			StringBuilder errorBuilder = new StringBuilder(
					"An error occurred while processing the query http response for ");
			errorBuilder.append(q);
			if ((e instanceof SocketTimeoutException || e instanceof NoRouteToHostException)) {

				errorBuilder.insert(0, "The connection timed out while closing the http connection. ");

				throw new OperationTimeoutException(errorBuilder.toString(), e);
			} else {

				LOGGER.error(
						"An error occurred while processing the queuery http response. Occurrence while processing the http response to the queuey request for: {1}, exception message: {0}",
						e.getLocalizedMessage(), q);
				LOGGER.info(
						"An error occurred while processing the queuery http response. Occurrence while processing the http response to the queuey request for: {1}, exception message: {0}",
						e, q);
				throw new ConnectorIOException(errorBuilder.toString(), e);
			}
		} finally {
			try {
				response.close();
			} catch (IOException e) {

				if (q == null) {
					q = "the full resource representation";
				}

				StringBuilder errorBuilder = new StringBuilder(
						"An error occurred while processing the query http response for ");
				errorBuilder.append(q);
				if ((e instanceof SocketTimeoutException || e instanceof NoRouteToHostException)) {

					errorBuilder.insert(0, "The connection timed out while closing the http connection. ");

					throw new OperationTimeoutException(errorBuilder.toString(), e);
				} else {

					LOGGER.error(
							"An error occurred while processing the queuery http response and closing the http connection. Occurrence while processing the http response to the queuey request for: {1}, exception message: {0}",
							e.getLocalizedMessage(), q);
					LOGGER.info(
							"An error occurred while processing the queuery http response and closing the http connection. Occurrence while processing the http response to the queuey request for: {1}, exception message: {0}",
							e, q);
					throw new ConnectorIOException(errorBuilder.toString(), e);
				}

			}
		}
	}

Try With Resources try(CloseableHttpResponse response=(CloseableHttpResponse)httpClient.execute(httpGet)) in method public query(query Filter, queryUriSnippet StringBuilder, resourceEndPoint String, resultHandler ResultsHandler, conf ScimConnectorConfiguration) : void from class com.evolveum.polygon.scim.StandardScimHandlingStrategy