use of cz.metacentrum.perun.core.api.exceptions.rt.InternalErrorRuntimeException in project perun by CESNET.
the class ExtSourceSqlComplex method querySource.
protected List<Map<String, String>> querySource(String query, String searchString, int maxResults) throws InternalErrorException {
PreparedStatement st = null;
ResultSet rs = null;
if (getAttributes().get("url") == null) {
throw new InternalErrorException("url attribute is required");
}
//log.debug("Searching for '{}' using query {} in external source 'url:{}'", new Object[] {searchString, query, (String) getAttributes().get("url")});
log.debug("Searching for '{}' in external source 'url:{}'", new Object[] { searchString, (String) getAttributes().get("url") });
// Register driver if the attribute has been defined
if (getAttributes().get("driver") != null) {
try {
Class.forName(getAttributes().get("driver"));
} catch (ClassNotFoundException e) {
throw new InternalErrorException("Driver " + getAttributes().get("driver") + " cannot be registered", e);
}
}
try {
// Check if we have existing connection. In case of Oracle also checks the connection validity
if (this.con == null || (this.isOracle && !this.con.isValid(0))) {
this.createConnection();
}
st = this.con.prepareStatement(query);
// Substitute the ? in the query by the seachString
if (searchString != null && !searchString.isEmpty()) {
for (int i = st.getParameterMetaData().getParameterCount(); i > 0; i--) {
st.setString(i, searchString);
}
}
// Limit results
if (maxResults > 0) {
st.setMaxRows(maxResults);
}
rs = st.executeQuery();
List<Map<String, String>> subjects = new ArrayList<Map<String, String>>();
log.trace("Query {}", query);
while (rs.next()) {
Map<String, String> map = new HashMap<String, String>();
try {
map.put("firstName", rs.getString("firstName"));
} catch (SQLException e) {
// If the column doesn't exists, ignore it
map.put("firstName", null);
}
try {
map.put("lastName", rs.getString("lastName"));
} catch (SQLException e) {
// If the column doesn't exists, ignore it
map.put("lastName", null);
}
try {
map.put("middleName", rs.getString("middleName"));
} catch (SQLException e) {
// If the column doesn't exists, ignore it
map.put("middleName", null);
}
try {
map.put("titleBefore", rs.getString("titleBefore"));
} catch (SQLException e) {
// If the column doesn't exists, ignore it
map.put("titleBefore", null);
}
try {
map.put("titleAfter", rs.getString("titleAfter"));
} catch (SQLException e) {
// If the column doesn't exists, ignore it
map.put("titleAfter", null);
}
try {
map.put("login", rs.getString("login"));
} catch (SQLException e) {
// If the column doesn't exists, ignore it
map.put("login", null);
}
for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) {
String columnName = rs.getMetaData().getColumnLabel(i);
log.trace("Iterating through attribute {}", columnName);
// Now go through all other attributes. If the column name(=attribute name) contains ":", then it represents an attribute
if (columnName.contains(":")) {
// Decode the attribute name (column name has limited size, so we need to code the attribute names)
// Coded attribute name: x:y:z
// x - m: member, u: user, f: facility, r: resource, mr: member-resource, uf: user-facility, h: host, v: vo, g: group, gr: group-resource
// y - d: def, o: opt
String[] attributeRaw = columnName.split(":", 3);
String attributeName = null;
if (!attributeNameMapping.containsKey(attributeRaw[0])) {
log.error("Unknown attribute type '{}' for user {} {}, attributeRaw {}", new Object[] { attributeRaw[0], map.get("firstName"), map.get("lastName"), attributeRaw });
} else if (!attributeNameMapping.containsKey(attributeRaw[1])) {
log.error("Unknown attribute type '{}' for user {} {}, attributeRaw {}", new Object[] { attributeRaw[1], map.get("firstName"), map.get("lastName"), attributeRaw });
} else {
attributeName = attributeNameMapping.get(attributeRaw[0]) + attributeNameMapping.get(attributeRaw[1]) + attributeRaw[2];
if (!Objects.equals(rs.getMetaData().getColumnTypeName(i), "BLOB")) {
// trace only string data
log.trace("Adding attribute {} with value {}", attributeName, rs.getString(i));
} else {
log.trace("Adding attribute {} with BLOB value", attributeName);
}
}
String attributeValue = null;
if (Objects.equals(rs.getMetaData().getColumnTypeName(i), "BLOB")) {
// source column is binary
try {
InputStream inputStream = rs.getBinaryStream(i);
if (inputStream != null) {
ByteArrayOutputStream result = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) != -1) {
result.write(buffer, 0, length);
}
byte[] bytes = Base64.encodeBase64(result.toByteArray());
attributeValue = new String(bytes, "UTF-8");
}
} catch (IOException ex) {
log.error("Unable to read BLOB for column {}", columnName);
throw new InternalErrorException("Unable to read BLOB data for column: " + columnName, ex);
}
} else {
// let driver to convert type to string
attributeValue = rs.getString(i);
}
if (rs.wasNull()) {
map.put(attributeName, null);
} else {
map.put(attributeName, attributeValue);
}
} else if (columnName.toLowerCase().startsWith(ExtSourcesManagerImpl.USEREXTSOURCEMAPPING)) {
// additionalUserExtSources, we must do lower case because some DBs changes lower to upper
map.put(columnName.toLowerCase(), rs.getString(i));
log.trace("Adding attribute {} with value {}", columnName, rs.getString(i));
}
}
subjects.add(map);
}
log.debug("Returning {} subjects from external source {} for searchString {}", new Object[] { subjects.size(), this, searchString });
return subjects;
} catch (SQLException e) {
log.error("SQL exception during searching for subject '{}'", query);
throw new InternalErrorRuntimeException(e);
} finally {
try {
if (rs != null)
rs.close();
if (st != null)
st.close();
} catch (SQLException e) {
log.error("SQL exception during closing the resultSet or statement, while searching for subject '{}'", query);
throw new InternalErrorRuntimeException(e);
}
}
}
use of cz.metacentrum.perun.core.api.exceptions.rt.InternalErrorRuntimeException in project perun by CESNET.
the class ExtSourcesManagerImpl method loadExtSourcesDefinitions.
/**
* Loads the extSources definitions from the XML configuration file.
* All data from the extSouces XML file are synchronized with the DB.
*
* @throws InternalErrorException
*/
public void loadExtSourcesDefinitions(PerunSession sess) {
try {
// Load the XML file
BufferedInputStream is = new BufferedInputStream(new FileInputStream(ExtSourcesManager.CONFIGURATIONFILE));
if (is == null) {
throw new InternalErrorException("Cannot load configuration file " + ExtSourcesManager.CONFIGURATIONFILE);
}
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(is);
doc.getDocumentElement().normalize();
// Check if the root element is "extSources"
if (!doc.getDocumentElement().getNodeName().equals("extSources")) {
throw new InternalErrorException("perun-extSources.xml doesn't contain extSources as root element");
}
// Get all defined extSources
NodeList extSourcesNodes = doc.getElementsByTagName("extSource");
for (int extSourceSeq = 0; extSourceSeq < extSourcesNodes.getLength(); extSourceSeq++) {
// Get each extSource
Node extSourceNode = extSourcesNodes.item(extSourceSeq);
if (extSourceNode.getNodeType() == Node.ELEMENT_NODE) {
Element extSourceElement = (Element) extSourceNode;
// Get extSource name
String extSourceName = extSourceElement.getElementsByTagName("name").item(0).getChildNodes().item(0).getNodeValue();
if (extSourceName == null) {
throw new InternalErrorException("extSource doesn't have defined name");
}
// Get extSource type
String extSourceType = extSourceElement.getElementsByTagName("type").item(0).getChildNodes().item(0).getNodeValue();
if (extSourceType == null) {
throw new InternalErrorException("extSource " + extSourceName + " doesn't have defined type");
}
// Get all extSource attributes
NodeList attributeNodes = extSourceElement.getElementsByTagName("attribute");
Map<String, String> attributes = new HashMap<String, String>();
for (int attributeSeq = 0; attributeSeq < attributeNodes.getLength(); attributeSeq++) {
Element elem = (Element) attributeNodes.item(attributeSeq);
if (elem.getNodeType() == Node.ELEMENT_NODE) {
String attrName = elem.getAttribute("name");
String attrValue = null;
if (elem.getChildNodes() != null && elem.getChildNodes().item(0) != null) {
attrValue = elem.getChildNodes().item(0).getNodeValue();
}
attributes.put(attrName, attrValue);
}
}
// Check if the extSource
try {
ExtSource extSource;
try {
extSource = this.getExtSourceByName(sess, extSourceName);
extSource.setName(extSourceName);
extSource.setType(extSourceType);
// ExtSource exists, so check values and potentionally update it
self.updateExtSource(sess, extSource, attributes);
} catch (ExtSourceNotExistsException e) {
// ExtSource doesn't exist, so create it
extSource = new ExtSource();
extSource.setName(extSourceName);
extSource.setType(extSourceType);
extSource = self.createExtSource(sess, extSource, attributes);
}
} catch (RuntimeException e) {
throw new InternalErrorException(e);
}
}
}
} catch (FileNotFoundException e) {
log.warn("No external source configuration file found.");
} catch (Exception e) {
log.error("Cannot initialize ExtSourceManager.");
throw new InternalErrorRuntimeException(e);
}
}
use of cz.metacentrum.perun.core.api.exceptions.rt.InternalErrorRuntimeException in project perun by CESNET.
the class Auditable method compareByCreatedAt.
public int compareByCreatedAt(Auditable auditable) {
if (auditable == null || auditable.createdAt == null || this.createdAt == null) {
throw new InternalErrorRuntimeException(new NullPointerException("There is null pointer in auditable object or in createdAt"));
}
Date date1;
try {
date1 = BeansUtils.getDateFormatter().parse(createdAt);
} catch (Exception ex) {
throw new InternalErrorRuntimeException("There is problem with parsing createdAt in object " + this, ex);
}
Date date2;
try {
date2 = BeansUtils.getDateFormatter().parse(auditable.getCreatedAt());
} catch (Exception ex) {
throw new InternalErrorRuntimeException("There is problem with parsing createdAt in object " + auditable, ex);
}
return date1.compareTo(date2);
}
use of cz.metacentrum.perun.core.api.exceptions.rt.InternalErrorRuntimeException in project perun by CESNET.
the class ExtSourceSql method querySource.
protected List<Map<String, String>> querySource(String query, String searchString, int maxResults) throws InternalErrorException {
PreparedStatement st = null;
ResultSet rs = null;
if (getAttributes().get("url") == null) {
throw new InternalErrorException("url attribute is required");
}
//log.debug("Searching for '{}' using query {} in external source 'url:{}'", new Object[] {searchString, query, (String) getAttributes().get("url")});
log.debug("Searching for '{}' in external source 'url:{}'", new Object[] { searchString, (String) getAttributes().get("url") });
// Register driver if the attribute has been defined
if (getAttributes().get("driver") != null) {
try {
Class.forName(getAttributes().get("driver"));
} catch (ClassNotFoundException e) {
throw new InternalErrorException("Driver " + getAttributes().get("driver") + " cannot be registered", e);
}
}
try {
// Check if we have existing connection. In case of Oracle also checks the connection validity
if (this.con == null || (this.isOracle && !this.con.isValid(0))) {
this.createConnection();
}
st = this.con.prepareStatement(query);
// Substitute the ? in the query by the seachString
if (searchString != null && !searchString.isEmpty()) {
for (int i = st.getParameterMetaData().getParameterCount(); i > 0; i--) {
st.setString(i, searchString);
}
}
// Limit results
if (maxResults > 0) {
st.setMaxRows(maxResults);
}
rs = st.executeQuery();
List<Map<String, String>> subjects = new ArrayList<Map<String, String>>();
log.trace("Query {}", query);
while (rs.next()) {
Map<String, String> map = new HashMap<String, String>();
try {
map.put("firstName", rs.getString("firstName"));
} catch (SQLException e) {
// If the column doesn't exists, ignore it
map.put("firstName", null);
}
try {
map.put("lastName", rs.getString("lastName"));
} catch (SQLException e) {
// If the column doesn't exists, ignore it
map.put("lastName", null);
}
try {
map.put("middleName", rs.getString("middleName"));
} catch (SQLException e) {
// If the column doesn't exists, ignore it
map.put("middleName", null);
}
try {
map.put("titleBefore", rs.getString("titleBefore"));
} catch (SQLException e) {
// If the column doesn't exists, ignore it
map.put("titleBefore", null);
}
try {
map.put("titleAfter", rs.getString("titleAfter"));
} catch (SQLException e) {
// If the column doesn't exists, ignore it
map.put("titleAfter", null);
}
try {
map.put("login", rs.getString("login"));
} catch (SQLException e) {
// If the column doesn't exists, ignore it
map.put("login", null);
}
for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) {
String columnName = rs.getMetaData().getColumnLabel(i);
log.trace("Iterating through attribute {}", columnName);
// Now go through all other attributes. If the column name(=attribute name) contains ":", then it represents an attribute
if (columnName.contains(":")) {
// Decode the attribute name (column name has limited size, so we need to code the attribute names)
// Coded attribute name: x:y:z
// x - m: member, u: user, f: facility, r: resource, mr: member-resource, uf: user-facility, h: host, v: vo, g: group, gr: group-resource
// y - d: def, o: opt
String[] attributeRaw = columnName.split(":", 3);
String attributeName = null;
if (!attributeNameMapping.containsKey(attributeRaw[0])) {
log.error("Unknown attribute type '{}' for user {} {}, attributeRaw {}", new Object[] { attributeRaw[0], map.get("firstName"), map.get("lastName"), attributeRaw });
} else if (!attributeNameMapping.containsKey(attributeRaw[1])) {
log.error("Unknown attribute type '{}' for user {} {}, attributeRaw {}", new Object[] { attributeRaw[1], map.get("firstName"), map.get("lastName"), attributeRaw });
} else {
attributeName = attributeNameMapping.get(attributeRaw[0]) + attributeNameMapping.get(attributeRaw[1]) + attributeRaw[2];
if (!Objects.equals(rs.getMetaData().getColumnTypeName(i), "BLOB")) {
// trace only string data
log.trace("Adding attribute {} with value {}", attributeName, rs.getString(i));
} else {
log.trace("Adding attribute {} with BLOB value", attributeName);
}
}
String attributeValue = null;
if (Objects.equals(rs.getMetaData().getColumnTypeName(i), "BLOB")) {
// source column is binary
try {
InputStream inputStream = rs.getBinaryStream(i);
if (inputStream != null) {
ByteArrayOutputStream result = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) != -1) {
result.write(buffer, 0, length);
}
byte[] bytes = Base64.encodeBase64(result.toByteArray());
attributeValue = new String(bytes, "UTF-8");
}
} catch (IOException ex) {
log.error("Unable to read BLOB for column {}", columnName);
throw new InternalErrorException("Unable to read BLOB data for column: " + columnName, ex);
}
} else {
// let driver to convert type to string
attributeValue = rs.getString(i);
}
if (rs.wasNull()) {
map.put(attributeName, null);
} else {
map.put(attributeName, attributeValue);
}
} else if (columnName.toLowerCase().startsWith(ExtSourcesManagerImpl.USEREXTSOURCEMAPPING)) {
// additionalUserExtSources, we must do lower case because some DBs changes lower to upper
map.put(columnName.toLowerCase(), rs.getString(i));
log.trace("Adding attribute {} with value {}", columnName, rs.getString(i));
}
}
subjects.add(map);
}
log.debug("Returning {} subjects from external source {} for searchString {}", new Object[] { subjects.size(), this, searchString });
return subjects;
} catch (SQLException e) {
log.error("SQL exception during searching for subject '{}'", query);
throw new InternalErrorRuntimeException(e);
} finally {
try {
if (rs != null)
rs.close();
if (st != null)
st.close();
} catch (SQLException e) {
log.error("SQL exception during closing the resultSet or statement, while searching for subject '{}'", query);
throw new InternalErrorRuntimeException(e);
}
}
}
use of cz.metacentrum.perun.core.api.exceptions.rt.InternalErrorRuntimeException in project perun by CESNET.
the class ExtSourcesManagerImpl method createExtSource.
public ExtSource createExtSource(PerunSession sess, ExtSource extSource, Map<String, String> attributes) throws InternalErrorException, ExtSourceExistsException {
Utils.notNull(extSource.getName(), "extSource.getName()");
Utils.notNull(extSource.getType(), "extSource.getType()");
try {
// Check if the extSources already exists
if (0 < jdbc.queryForInt("select count(id) from ext_sources where name=? and type=?", extSource.getName(), extSource.getType())) {
throw new ExtSourceExistsException(extSource);
}
// Get a new Id
int newId = Utils.getNewId(jdbc, "ext_sources_id_seq");
jdbc.update("insert into ext_sources (id, name, type, created_by,created_at,modified_by,modified_at,created_by_uid,modified_by_uid) " + "values (?,?,?,?," + Compatibility.getSysdate() + ",?," + Compatibility.getSysdate() + ",?,?)", newId, extSource.getName(), extSource.getType(), sess.getPerunPrincipal().getActor(), sess.getPerunPrincipal().getActor(), sess.getPerunPrincipal().getUserId(), sess.getPerunPrincipal().getUserId());
extSource.setId(newId);
ExtSource es;
// Get the instance by the type of the extSource
try {
Class<?> extSourceClass = Class.forName((String) extSource.getType());
es = (ExtSource) extSourceClass.newInstance();
} catch (ClassNotFoundException e) {
throw new InternalErrorException(e);
} catch (InstantiationException e) {
throw new InternalErrorRuntimeException(e);
} catch (IllegalAccessException e) {
throw new InternalErrorRuntimeException(e);
}
// Set the properties
es.setId(extSource.getId());
es.setName(extSource.getName());
es.setType(extSource.getType());
// Now store the attributes
if (attributes != null) {
Iterator<String> i = attributes.keySet().iterator();
while (i.hasNext()) {
String attr_name = i.next();
jdbc.update("insert into ext_sources_attributes (attr_name, attr_value, ext_sources_id,created_by, created_at, modified_by, modified_at, created_by_uid, modified_by_uid) " + "values (?,?,?,?," + Compatibility.getSysdate() + ",?," + Compatibility.getSysdate() + ",?,?)", attr_name, attributes.get(attr_name), extSource.getId(), sess.getPerunPrincipal().getActor(), sess.getPerunPrincipal().getActor(), sess.getPerunPrincipal().getUserId(), sess.getPerunPrincipal().getUserId());
}
}
// Assign newly created extSource
extSource = es;
return extSource;
} catch (RuntimeException e) {
throw new InternalErrorException(e);
}
}
Aggregations