use of cz.metacentrum.perun.core.api.exceptions.InternalErrorException in project perun by CESNET.
the class ExtSourceISMU method querySource.
protected List<Map<String, String>> querySource(String query, String searchString, int maxResults) throws InternalErrorException {
// Get the URL, if query was provided it has precedence over url attribute defined in extSource
String url = null;
if (query != null && !query.isEmpty()) {
url = query;
} else if (getAttributes().get("url") != null) {
url = getAttributes().get("url");
} else {
throw new InternalErrorException("url attribute or query is required");
}
log.debug("Searching in external source url:'{}'", url);
// If there is a search string, replace all occurences of the * with the searchstring
if (searchString != null && searchString != "") {
url.replaceAll("\\*", searchString);
}
;
try {
URL u = new URL(url);
// Check supported protocols
HttpURLConnection http = null;
if (u.getProtocol().equals("https")) {
http = (HttpsURLConnection) u.openConnection();
} else if (u.getProtocol().equals("http")) {
http = (HttpURLConnection) u.openConnection();
} else {
throw new InternalErrorException("Protocol " + u.getProtocol() + " is not supported by this extSource.");
}
// Prepare the basic auth, if the username and password was specified
if (getAttributes().get("user") != null && getAttributes().get("password") != null) {
String val = (new StringBuffer(getAttributes().get("user")).append(":").append(getAttributes().get("password"))).toString();
Base64 encoder = new Base64();
String base64Encoded = new String(encoder.encode(val.getBytes()));
// Java bug : http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6459815
base64Encoded = base64Encoded.trim();
String authorizationString = "Basic " + base64Encoded;
http.setRequestProperty("Authorization", authorizationString);
}
http.setAllowUserInteraction(false);
http.setRequestMethod("GET");
http.connect();
InputStream is = http.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line = null;
List<Map<String, String>> subjects = new ArrayList<Map<String, String>>();
while ((line = reader.readLine()) != null) {
Map<String, String> map = new HashMap<String, String>();
// Each line looks like:
// UCO ;; ;"title before. title before. firstName lastName, title after
// 39700;;“RNDr. Michal Procházka";Procházka;Michal;
// Parse the line
String[] entries = line.split(";");
// Get the UCO
if (entries[0].equals("")) {
// skip this subject, because it doesn't have UCO defined
continue;
}
String login = entries[0];
if (login.isEmpty())
login = null;
map.put("login", login);
String name = entries[2];
// Remove "" from name
name.replaceAll("^\"|\"$", "");
// entries[3] contains name of the user, so parse it to get titleBefore, firstName, lastName and titleAfter in separate fields
map.putAll(Utils.parseCommonName(name));
// Add additional userExtSource for MU IdP with loa 2
map.put(ExtSourcesManagerImpl.USEREXTSOURCEMAPPING + "1", "https://idp2.ics.muni.cz/idp/shibboleth|cz.metacentrum.perun.core.impl.ExtSourceIdp|" + login + "@muni.cz|2");
subjects.add(map);
}
return subjects;
} catch (IOException e) {
throw new InternalErrorException(e);
} catch (Exception e) {
throw new InternalErrorException(e);
}
}
use of cz.metacentrum.perun.core.api.exceptions.InternalErrorException 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.InternalErrorException 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.InternalErrorException in project perun by CESNET.
the class FacilitiesManagerImpl method getFacilityContactGroup.
@Override
public ContactGroup getFacilityContactGroup(PerunSession sess, Facility facility, String name) throws InternalErrorException, FacilityContactNotExistsException {
try {
List<ContactGroup> contactGroups = jdbc.query("select " + facilityContactsMappingSelectQueryWithAllEntities + " from facility_contacts " + "left join facilities on facilities.id=facility_contacts.facility_id " + "left join owners on owners.id=facility_contacts.owner_id " + "left join users on users.id=facility_contacts.user_id " + "left join groups on groups.id=facility_contacts.group_id " + "where facility_contacts.facility_id=? and facility_contacts.name=?", FACILITY_CONTACT_MAPPER, facility.getId(), name);
contactGroups = mergeContactGroups(contactGroups);
if (contactGroups.size() == 1) {
return contactGroups.get(0);
} else {
throw new InternalErrorException("Merging group contacts for facility " + facility + " and contact name " + name + " failed, more than 1 object returned " + name);
}
} catch (EmptyResultDataAccessException ex) {
throw new FacilityContactNotExistsException(facility, name);
} catch (RuntimeException ex) {
throw new InternalErrorException(ex);
}
}
use of cz.metacentrum.perun.core.api.exceptions.InternalErrorException in project perun by CESNET.
the class ExtSourcePerun method covertRichUserToSubject.
private Map<String, String> covertRichUserToSubject(RichUser richUser) throws InternalErrorException {
Map<String, String> richUserInMap = new HashMap<String, String>();
String mapping = getAttributes().get("xmlMapping");
String[] mappingArray = mapping.split(",\n");
//Get user login
String login = "";
for (UserExtSource ues : richUser.getUserExtSources()) {
if (ues.getExtSource() != null && ues.getExtSource().getName().equals(extSourceNameForLogin)) {
login = ues.getLogin();
break;
}
}
//Null login is not allowed there
if (login == null)
throw new InternalErrorException("There is missing login for user " + richUser + " and extSource " + extSourceNameForLogin);
for (int i = 0; i < mappingArray.length; i++) {
String attr = mappingArray[i].trim();
int index = attr.indexOf("=");
if (index <= 0)
throw new InternalErrorException("There is no text in xmlMapping attribute or there is no '=' character.");
String name = attr.substring(0, index);
String value = attr.substring(index + 1);
Matcher attributeMatcher = attributePattern.matcher(value);
//Try to find perun attributes in value part
if (attributeMatcher.find()) {
if (attributeMatcher.group(1).equals("login")) {
value = attributeMatcher.replaceFirst(login);
} else {
String replacement = lookingForValueInRichUserAttributes(attributeMatcher.group(1), richUser);
if (replacement == null)
replacement = "";
value = attributeMatcher.replaceFirst(replacement);
//If whole value is empty because of replacement, it means null for us
if (value.isEmpty())
value = null;
}
} else if (value.startsWith("urn:perun:")) {
//DEPRECATED, but need to be first removed from all settings of PerunExtSource in perun-extSource.xml file
//It is probably old way how to use attribute (without {}) so try to find value for it
value = lookingForValueInRichUserAttributes(value, richUser);
}
//If nothing found, let the value be the same, it is probably static value (without any attribute)
richUserInMap.put(name.trim(), value);
}
return richUserInMap;
}
Aggregations