use of cz.metacentrum.perun.core.api.exceptions.InternalErrorException in project perun by CESNET.
the class ExtSourceXML method extractValueByRegex.
/**
* Get regex in format 'regex/replacement' and value to get data from.
* Use regex and replacement to get data from value.
*
* IMPORTANT: Regex must be always in format 'regex/replacement' and must have
* exactly 1 existence of character '/' ex. '[abc](a)[b]/$1'
*
* @param value some string
* @param regex regex in format 'regex/replacement'
* @return extracted string from value by regex
*
* @throws InternalErrorException
*/
protected String extractValueByRegex(String value, String regex) throws InternalErrorException {
//trim value to erase newlines and spaces before and after value
value = value.trim();
//regex need to be separate to 2 parts (regex) and (replacement) separated by backslash - ex 'regex/replacement'
Matcher match = pattern.matcher(regex);
//need to separate regex to regexPart and replacementPart
String regexPart;
String replacementPart;
if (match.find()) {
int i = match.end();
if (match.find())
throw new InternalErrorException("There is more then one separating forward slash in regex without escaping.");
while (regex.charAt(i) != '/') {
i--;
if (i < 0)
throw new InternalErrorException("Index of forward slash not found.");
}
regexPart = regex.substring(0, i);
replacementPart = regex.substring(i + 1);
} else {
throw new InternalErrorException("There is no replacement in regex.");
}
//use regex and replacement to get string from value
value = value.replaceAll(regexPart, replacementPart);
return value;
}
use of cz.metacentrum.perun.core.api.exceptions.InternalErrorException in project perun by CESNET.
the class ExtSourceXML method createTwoWaySSLConnection.
/**
* Get https uri of xml document and create two way ssl connection using truststore and keystore.
*
* @param uri https uri to xml document
* @return input stream with xml document
*
* @throws IOException if there is some input/output error
* @throws InternalErrorException if some variables are not correctly filled
*/
protected InputStream createTwoWaySSLConnection(String uri) throws IOException, InternalErrorException {
if (uri == null || uri.isEmpty())
throw new InternalErrorException("Uri must be filled, can't be null or empty.");
/*//KeyStore data
String keyStore = getAttributes().get("keyStore");
String keyStorePass = getAttributes().get("keyStorePass");
String keyStoreType = getAttributes().get("keyStoreType");
if(keyStore == null || keyStorePass == null || keyStoreType == null) {
throw new InternalErrorException("KeystorePath, KeystorePass and KeystoreType must be filled. Please look into configuration file.");
}
//TrustStore data
String trustStore = getAttributes().get("trustStore");
String trustStorePass = getAttributes().get("trustStorePass");
if(trustStore == null || trustStorePass == null) {
throw new InternalErrorException("TrustStorePath and TrustStorePass must be filled. Please look into configuration file.");
}
//set necessary keystore properties - using a p12 file
System.setProperty("javax.net.ssl.keyStore", keyStore);
System.setProperty("javax.net.ssl.keyStorePassword", keyStorePass);
System.setProperty("javax.net.ssl.keyStoreType", keyStoreType);
//set necessary truststore properties - using JKS
System.setProperty("javax.net.ssl.trustStore", trustStore);
System.setProperty("javax.net.ssl.trustStorePassword", trustStorePass);
// register a https protocol handler - this may be required for previous JDK versions
System.setProperty("java.protocol.handler.pkgs","com.sun.net.ssl.internal.www.protocol");*/
//prepare sslFactory
SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault();
HttpsURLConnection.setDefaultSSLSocketFactory(factory);
URL myurl = new URL(uri);
con = (HttpURLConnection) myurl.openConnection();
//set request header if is required (set in extSource xml)
String reqHeaderKey = getAttributes().get("requestHeaderKey");
String reqHeaderValue = getAttributes().get("requestHeaderValue");
if (reqHeaderKey != null) {
if (reqHeaderValue == null)
reqHeaderValue = "";
con.setRequestProperty(reqHeaderKey, reqHeaderValue);
}
int responseCode = con.getResponseCode();
if (responseCode == 200) {
InputStream is = con.getInputStream();
return is;
}
throw new InternalErrorException("Wrong response code while opening connection on uri '" + uri + "'. Response code: " + responseCode);
}
use of cz.metacentrum.perun.core.api.exceptions.InternalErrorException in project perun by CESNET.
the class ExtSourceXML method getValueFromXpath.
/**
* Get xml Node and xpath expression to get value from node by this xpath.
*
* @param node node for getting value from
* @param xpathExpression expression for xpath to looking for value in node
* @return string extracted from node by xpath
* @throws InternalErrorException
*/
protected String getValueFromXpath(Node node, String xpathExpression) throws InternalErrorException {
//Prepare xpath expression
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
XPathExpression expr;
try {
expr = xpath.compile(xpathExpression);
} catch (XPathExpressionException ex) {
throw new InternalErrorException("Error when compiling xpath query.", ex);
}
String text;
try {
text = (String) expr.evaluate(node, XPathConstants.STRING);
} catch (XPathExpressionException ex) {
throw new InternalErrorException("Error when evaluate xpath query on node.", ex);
}
return text;
}
use of cz.metacentrum.perun.core.api.exceptions.InternalErrorException in project perun by CESNET.
the class ExtSourceXML method xpathParsing.
/**
* Get query and maxResults.
* Prepare document and xpathExpression by query.
* Get all nodes by xpath from document and parse them one by one.
*
* The way of xml take from "file" or "uri" (configuration file)
*
* @param query xpath query from config file
* @param maxResults never get more than maxResults results (0 mean unlimited)
*
* @return List of results, where result is Map<String,String> like <name, value>
* @throws InternalErrorException
*/
protected List<Map<String, String>> xpathParsing(String query, int maxResults) throws InternalErrorException {
//Prepare result list
List<Map<String, String>> subjects = new ArrayList<Map<String, String>>();
//Create new document factory builder
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
try {
builder = factory.newDocumentBuilder();
} catch (ParserConfigurationException ex) {
throw new InternalErrorException("Error when creating newDocumentBuilder.", ex);
}
Document doc;
try {
if (file != null && !file.isEmpty()) {
doc = builder.parse(file);
} else if (uri != null && !uri.isEmpty()) {
doc = builder.parse(this.createTwoWaySSLConnection(uri));
} else {
throw new InternalErrorException("Document can't be parsed, because there is no way (file or uri) to this document in xpathParser.");
}
} catch (SAXParseException ex) {
throw new InternalErrorException("Error when parsing uri by document builder.", ex);
} catch (SAXException ex) {
throw new InternalErrorException("Problem with parsing is more complex, not only invalid characters.", ex);
} catch (IOException ex) {
throw new InternalErrorException("Error when parsing uri by document builder. Problem with input or output.", ex);
}
//Prepare xpath expression
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
XPathExpression queryExpr;
try {
queryExpr = xpath.compile(query);
} catch (XPathExpressionException ex) {
throw new InternalErrorException("Error when compiling xpath query.", ex);
}
//Call query on document node and get back nodesets
NodeList nodeList;
try {
nodeList = (NodeList) queryExpr.evaluate(doc, XPathConstants.NODESET);
} catch (XPathExpressionException ex) {
throw new InternalErrorException("Error when evaluate xpath query on document.", ex);
}
//Test if there is any nodeset in result
if (nodeList.getLength() == 0) {
//There is no results, return empty subjects
return subjects;
}
//Iterate through nodes and convert them to Map<String,String>
for (int i = 0; i < nodeList.getLength(); i++) {
Node singleNode = nodeList.item(i);
// remove node from original structure in order to keep access time constant (otherwise is exp.)
singleNode.getParentNode().removeChild(singleNode);
Map<String, String> map = convertNodeToMap(singleNode);
if (map != null)
subjects.add(map);
//Reducing results by maxResults
if (maxResults > 0) {
if (subjects.size() >= maxResults)
break;
}
}
this.close();
return subjects;
}
use of cz.metacentrum.perun.core.api.exceptions.InternalErrorException in project perun by CESNET.
the class ExtSourcesManagerImpl method updateExtSource.
@Override
public void updateExtSource(PerunSession sess, ExtSource extSource, Map<String, String> attributes) throws ExtSourceNotExistsException, InternalErrorException {
ExtSource extSourceDb;
extSourceDb = this.getExtSourceById(sess, extSource.getId());
// Check the name
if (!extSourceDb.getName().equals(extSource.getName())) {
try {
jdbc.update("update ext_sources set name=? ,modified_by=?, modified_by_uid=?, modified_at=" + Compatibility.getSysdate() + " where id=?", extSource.getName(), sess.getPerunPrincipal().getActor(), sess.getPerunPrincipal().getUserId(), extSource.getId());
} catch (RuntimeException e) {
throw new InternalErrorException(e);
}
}
// Check the type
if (!extSourceDb.getType().equals(extSource.getType())) {
try {
jdbc.update("update ext_sources set type=?, modified_by=?, modified_by_uid=?, modified_at=" + Compatibility.getSysdate() + " where id=?", extSource.getType(), sess.getPerunPrincipal().getActor(), sess.getPerunPrincipal().getUserId(), extSource.getId());
} catch (RuntimeException e) {
throw new InternalErrorException(e);
}
}
// Check the attributes
if (!getAttributes(extSourceDb).equals(attributes)) {
log.debug("There is a change in attributes for {}", extSource);
try {
// Firstly delete all attributes, then store new ones
jdbc.update("delete from ext_sources_attributes where ext_sources_id=?", extSource.getId());
for (String attrName : attributes.keySet()) {
jdbc.update("insert into ext_sources_attributes (ext_sources_id, attr_name, attr_value, created_by, created_at, modified_by, modified_at, created_by_uid, modified_by_uid) " + "values (?,?,?,?," + Compatibility.getSysdate() + ",?," + Compatibility.getSysdate() + ",?,?)", extSource.getId(), attrName, attributes.get(attrName), sess.getPerunPrincipal().getActor(), sess.getPerunPrincipal().getActor(), sess.getPerunPrincipal().getUserId(), sess.getPerunPrincipal().getUserId());
}
} catch (RuntimeException e) {
throw new InternalErrorException(e);
}
}
}
Aggregations