All Downloads are FREE. Search and download functionalities are using the official Maven repository.

base.jee.api.sql.GetLocationByIP Maven / Gradle / Ivy

/**
 * Creative commons Attribution-NonCommercial license.
 *
 * http://creativecommons.org/licenses/by-nc/2.5/au/deed.en_GB
 *
 * NO WARRANTY IS GIVEN OR IMPLIED, USE AT YOUR OWN RISK.
 */
package base.jee.api.sql;

import base.Query;
import base.jee.api.model.Location;
import base.security.PermissionException;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import static base.jee.api.sql.util.IpLocation.ipLocation;
import static base.jee.Constants.MAX_IP_ADDRESS_LENGTH;

public class GetLocationByIP extends Query {

	private SqlAPI api;
	private String ip;

	public GetLocationByIP() {
	}

	public GetLocationByIP(SqlAPI api, String ip) throws PermissionException {

		if(api == null) {
			throw new IllegalArgumentException("Invalid parameter: api");
		}
		if(ip == null || ip.length() > MAX_IP_ADDRESS_LENGTH) {
			throw new IllegalArgumentException("Invalid IP address.");
		}

		this.api = api;
		this.ip = ip;
	}

	@Override
	public Query newWithParameters(Map parameters) throws PermissionException {
		return new GetLocationByIP(
				(SqlAPI)parameters.get("api"),
				(String)parameters.get("ip"));
	}

	public List execute() throws IOException {
		List results = new LinkedList<>();

		Connection c = null;

		try {
			c = api.getDataSource().getConnection();
			c.setAutoCommit(false);

			Location l = ipLocation(c, ip);
			if(l != null) {
				results.add(l);
			}

			c.rollback();
			c.close();
			c = null;
		} catch(SQLException e) {
			throw new IOException(e);
		} finally {
			if(c != null) {
				try { c.rollback(); } catch (SQLException e) {}
				try { c.close(); } catch (SQLException e) {}
			}
		}

		return results;
	}

	@Override
	public String getJsonParameters() {
		return "{" +
				"\"ip\":\"" + ip + "\"" +
				"}";
	}

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy