public static void waitForMetric(final JMXGet jmx, final String metricName, final int expectedValue) throws TimeoutException, InterruptedException { GenericTestUtils.waitFor(new Supplier<Boolean>() { @Override public Boolean get() { try { final int currentValue = Integer.parseInt(jmx.getValue(metricName)); LOG.info("Waiting for " + metricName + " to reach value " + expectedValue + ", current value = " + currentValue); return currentValue == expectedValue; } catch (Exception e) { throw new UnhandledException("Test failed due to unexpected exception", e); } } }, 1000, Integer.MAX_VALUE); }
/** * <p>Unescapes any Java literals found in the <code>String</code>. * For example, it will turn a sequence of <code>'\'</code> and * <code>'n'</code> into a newline character, unless the <code>'\'</code> * is preceded by another <code>'\'</code>.</p> * * @param str the <code>String</code> to unescape, may be null * @return a new unescaped <code>String</code>, <code>null</code> if null string input */ public static String unescape(String str) { if (str == null) { return null; } try { StringWriter writer = new StringWriter(str.length()); unescapeJava(writer, str); return writer.toString(); } catch (IOException ioe) { // this should never ever happen while writing to a StringWriter throw new UnhandledException(ioe); } }
private String parseMenuNode(int menuIndex, String menuTemplate, Properties menuAttributes, TagParser tagParser) { String modeAttribute = menuAttributes.getProperty("mode"); boolean modeIsRead = "read".equalsIgnoreCase(modeAttribute); boolean modeIsWrite = "write".equalsIgnoreCase(modeAttribute); boolean menuMode = parserParameters.isMenuMode(); if (menuMode && modeIsRead || !menuMode && modeIsWrite) { return ""; } try { NodeList menuNodes = new NodeList(menuTemplate, parserParameters.getDocumentRequest().getHttpServletRequest(), tagParser); DocumentRequest documentRequest = parserParameters.getDocumentRequest(); TextDocumentDomainObject document = (TextDocumentDomainObject) documentRequest.getDocument(); final MenuDomainObject menu = document.getMenu(menuIndex); StringWriter contentWriter = new StringWriter(); nodeMenu(new SimpleElement("menu", menuAttributes, menuNodes), contentWriter, menu, new Perl5Matcher(), tagParser); String content = contentWriter.toString(); return addMenuAdmin(menuIndex, menuMode, content, menu, documentRequest.getHttpServletRequest(), documentRequest.getHttpServletResponse(), menuAttributes.getProperty("label")); } catch (Exception e) { throw new UnhandledException(e); } }
private String tagVelocity(String content) { VelocityEngine velocityEngine = service.getVelocityEngine(parserParameters.getDocumentRequest().getUser()); VelocityContext velocityContext = new VelocityContext(); velocityContext.put("request", parserParameters.getDocumentRequest().getHttpServletRequest()); velocityContext.put("response", parserParameters.getDocumentRequest().getHttpServletResponse()); velocityContext.put("viewing", viewing); velocityContext.put("document", viewing.getTextDocument()); velocityContext.put("util", new VelocityTagUtil()); StringWriter stringWriter = new StringWriter(); try { velocityEngine.init(); velocityEngine.evaluate(velocityContext, stringWriter, null, content); } catch (Exception e) { throw new UnhandledException(e); } return stringWriter.toString(); }
private RoleId[] getRoleReferencesForUser(UserDomainObject user) { try { String sqlStr = SQL_SELECT_ALL_ROLES + ", user_roles_crossref" + " WHERE user_roles_crossref.role_id = roles.role_id" + " AND user_roles_crossref.user_id = ?"; final Object[] parameters = new String[]{"" + user.getId()}; String[][] sqlResult = (String[][]) services.getDatabase().execute(new SqlQueryCommand(sqlStr, parameters, Utility.STRING_ARRAY_ARRAY_HANDLER)); RoleId[] roleReferences = new RoleId[sqlResult.length]; for (int i = 0; i < sqlResult.length; i++) { String[] sqlRow = sqlResult[i]; roleReferences[i] = getRoleReferenceFromSqlResult(sqlRow); } return roleReferences; } catch (DatabaseException e) { throw new UnhandledException(e); } }
public String[] getAllRoleNames() { try { final Object[] parameters = new String[]{}; String[] roleNamesMinusUsers = services.getProcedureExecutor().executeProcedure(SPROC_GET_ALL_ROLES, parameters, new StringArrayResultSetHandler()); Set<String> roleNamesSet = new HashSet<>(); for (int i = 0; i < roleNamesMinusUsers.length; i += 2) { String roleName = roleNamesMinusUsers[i + 1]; roleNamesSet.add(roleName); } roleNamesSet.add(getRole(RoleId.USERS).getName()); String[] roleNames = roleNamesSet.toArray(new String[roleNamesSet.size()]); Arrays.sort(roleNames); return roleNames; } catch (DatabaseException e) { throw new UnhandledException(e); } }
public UserDomainObject[] getAllUsersWithRole(RoleDomainObject role) { try { if (null == role) { return new UserDomainObject[]{}; } final Object[] parameters = new String[]{"" + role.getId()}; String[] usersWithRole = services.getProcedureExecutor().executeProcedure(SPROC_GET_USERS_WHO_BELONGS_TO_ROLE, parameters, new StringArrayResultSetHandler()); UserDomainObject[] result = new UserDomainObject[usersWithRole.length / 2]; for (int i = 0; i < result.length; i++) { String userIdStr = usersWithRole[i * 2]; result[i] = getUser(Integer.parseInt(userIdStr)); } return result; } catch (DatabaseException e) { throw new UnhandledException(e); } }
void addRole(final RoleDomainObject role) throws RoleAlreadyExistsException, NameTooLongException { try { final int unionOfPermissionSetIds = getUnionOfRolePermissionIds(role); final int newRoleId = ((Number) services.getDatabase().execute(new TransactionDatabaseCommand() { public Object executeInTransaction(DatabaseConnection connection) throws DatabaseException { return connection.executeUpdateAndGetGeneratedKey(SQL_INSERT_INTO_ROLES, new String[]{ role.getName(), "" + unionOfPermissionSetIds}); } })).intValue(); role.setId(new RoleId(newRoleId)); } catch (IntegrityConstraintViolationException icvse) { throw new RoleAlreadyExistsException("A role with the name \"" + role.getName() + "\" already exists."); } catch (StringTruncationException stse) { throw new NameTooLongException("Role name too long: " + role.getName()); } catch (DatabaseException e) { throw new UnhandledException(e); } }
public PhoneNumber[] getUserPhoneNumbers(int userToChangeId) { try { final Object[] parameters = new String[]{ "" + userToChangeId}; String[][] phoneNumberData = (String[][]) services.getDatabase().execute(new SqlQueryCommand( "SELECT phones.number, phones.phonetype_id\n" + "FROM phones\n" + "WHERE phones.user_id = ?", parameters, Utility.STRING_ARRAY_ARRAY_HANDLER )); List<PhoneNumber> phoneNumbers = new ArrayList<>(); for (String[] row : phoneNumberData) { String phoneNumberString = row[0]; int phoneTypeId = Integer.parseInt(row[1]); PhoneNumberType phoneNumberType = PhoneNumberType.getPhoneNumberTypeById(phoneTypeId); PhoneNumber phoneNumber = new PhoneNumber(phoneNumberString, phoneNumberType); phoneNumbers.add(phoneNumber); } return phoneNumbers.toArray(new PhoneNumber[phoneNumbers.size()]); } catch (DatabaseException e) { throw new UnhandledException(e); } }
private RoleId[] getUserAdminRolesReferencesForUser(UserDomainObject loggedOnUser) { try { final Object[] parameters = new String[]{"" + loggedOnUser.getId()}; String[] roleIds = (String[]) services.getDatabase().execute(new SqlQueryCommand("SELECT role_id\n" + "FROM useradmin_role_crossref\n" + "WHERE user_id = ?", parameters, Utility.STRING_ARRAY_HANDLER)); List<RoleId> useradminPermissibleRolesList = new ArrayList<>(roleIds.length); for (String roleId : roleIds) { useradminPermissibleRolesList.add(new RoleId(Integer.parseInt(roleId))); } return useradminPermissibleRolesList.toArray(new RoleId[useradminPermissibleRolesList.size()]); } catch (DatabaseException e) { throw new UnhandledException(e); } }
private UserDomainObject synchExternalUserInImcms(String loginName, UserDomainObject externalUser, UserDomainObject imcmsUser) { externalUser.setImcmsExternal(true); addExternalRolesToUser(externalUser); if (null != imcmsUser) { externalUser.setRoleIds(imcmsUser.getRoleIds()); imcmsAuthenticatorAndUserMapperAndRole.saveUser(loginName, externalUser); } else { try { imcmsAuthenticatorAndUserMapperAndRole.addUser(externalUser); } catch (UserAlreadyExistsException shouldNotBeThrown) { throw new UnhandledException(shouldNotBeThrown); } } return imcmsAuthenticatorAndUserMapperAndRole.getUser(loginName); }
private UserDomainObject createUserFromLdapAttributes(Map<String, String> ldapAttributeValues) { UserDomainObject newlyFoundLdapUser = new UserDomainObject(); PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(newlyFoundLdapUser); try { for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { if (null == propertyDescriptor.getWriteMethod()) { continue; } String uncapitalizedPropertyName = propertyDescriptor.getName(); String capitalizedPropertyName = StringUtils.capitalize(uncapitalizedPropertyName); String ldapAttributeName = userPropertyNameToLdapAttributeNameMap.getProperty(capitalizedPropertyName); if (null != ldapAttributeName) { String ldapAttributeValue = ldapAttributeValues.get(ldapAttributeName); if (null != ldapAttributeValue) { BeanUtils.setProperty(newlyFoundLdapUser, uncapitalizedPropertyName, ldapAttributeValue); } } } } catch (IllegalAccessException | InvocationTargetException e) { throw new UnhandledException(e); } return newlyFoundLdapUser; }
public static boolean classIsSignedByCertificatesInKeyStore(Class clazz, KeyStore keyStore) { Object[] signers = clazz.getSigners(); if (null == signers) { return false; } for (Object signer : signers) { if (!(signer instanceof Certificate)) { return false; } Certificate certificate = (Certificate) signer; try { if (null == keyStore.getCertificateAlias(certificate)) { return false; } } catch (KeyStoreException e) { throw new UnhandledException(e); } } return true; }
public void sendMail(Mail mail) throws IOException { Email email = mail.getMail(); try { setEncryption(email); email.setHostName(host); email.setSmtpPort(port); email.setCharset("UTF-8"); email.send(); } catch (EmailException e) { if (Utility.throwableContainsMessageContaining(e, "no object DCH")) { throw new UnhandledException("\"no object DCH\" Likely cause: the activation jar-file cannot see the mail jar-file. Different ClassLoaders?", e); } else { throw new UnhandledException(e); } } }
/** * Separate the given string in lines using readline * * @param value * @return list of found lines */ public static List<String> getLines(String value) { final List<String> result = new ArrayList<String>(); if (value != null) { final BufferedReader br = new BufferedReader(new StringReader(value)); try { String l = br.readLine(); while (l!=null) { result.add(l); l = br.readLine(); } } catch (IOException e) { throw new UnhandledException(e); } } return result; }
/** * @param connection the JDBC connection to use */ public void execute(Connection connection) { final Injector injector = createInjector(); final SingleConnectionHibernateHelper hibernateHelper = createHibernateHelper(connection, injector); final FileDao fileDao = injector.getInstance(FileDao.class); final Set<DesignFileHandler> handlers = getAllDesignHandlers(fileDao); final Transaction transaction = hibernateHelper.beginTransaction(); try { final ArrayDao arrayDao = injector.getInstance(ArrayDao.class); final List<Long> arrayDesignIds = getArrayDesignIds(hibernateHelper, arrayDao); hibernateHelper.getCurrentSession().clear(); fixArrayDesigns(handlers, arrayDao, arrayDesignIds); transaction.commit(); } catch (final Exception e) { transaction.rollback(); throw new UnhandledException(e); } }
/** * {@inheritDoc} */ public void doHibernateExecute(final SingleConnectionHibernateHelper hibernateHelper) { try { List<Organism> allOrganisms = getAllOrganisms(hibernateHelper); Map<String, List<Organism>> nameToOrganismsListMap = buildNamesToOrganismsListMap(allOrganisms); for (List<Organism> organismsWithSameNameList : nameToOrganismsListMap.values()) { if (organismsWithSameNameList.size() > 1) { processOrganismsWithSameName(hibernateHelper, organismsWithSameNameList.get(0).getScientificName(), organismsWithSameNameList); } else if (organismsWithSameNameList.size() == 1) { Organism organism = organismsWithSameNameList.get(0); if (null != organism.getTermSource() && !ExperimentOntology.NCBI.getOntologyName().equals(organism.getTermSource().getName())) { organism.setTermSource(getNcbiTermSource(hibernateHelper)); } } } } catch (Exception exception) { throw new UnhandledException("Cannot fix the Organisms in DB.", exception); } }
/** * <p> * Unescapes the entities in a <code>String</code>. * </p> * * <p> * For example, if you have called addEntity("foo", 0xA1), unescape("&foo;") will return * "\u00A1" * </p> * * @param str * The <code>String</code> to escape. * @return A new escaped <code>String</code>. */ public String unescape(String str) { int firstAmp = str.indexOf('&'); if (firstAmp < 0) { return str; } else { StringWriter stringWriter = createStringWriter(str); try { this.doUnescape(stringWriter, str, firstAmp); } catch (IOException e) { // This should never happen because ALL the StringWriter methods called by #escape(Writer, String) // do not throw IOExceptions. throw new UnhandledException(e); } return stringWriter.toString(); } }
@Override public TemplateNames clone() { try { return (TemplateNames) super.clone(); } catch (CloneNotSupportedException e) { throw new UnhandledException(e); } }
private String loadFile(File file) { try { return fileLoader.getCachedFileString(file); } catch (IOException e) { throw new UnhandledException(e); } }
public Document createRssDocument(Channel channel) { try { DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = builderFactory.newDocumentBuilder(); Document xmlDocument = documentBuilder.newDocument(); appendRssElement(xmlDocument, channel); return xmlDocument; } catch (ParserConfigurationException e) { throw new UnhandledException(e); } }
private String includeEditing(Properties attributes, int no) { try { String label = getLabel(attributes); Integer includedDocumentId = document.getIncludedDocumentId(no); if (includeMode) { HttpServletRequest request = documentRequest.getHttpServletRequest(); HttpServletResponse response = documentRequest.getHttpServletResponse(); UserDomainObject user = documentRequest.getUser(); try { request.setAttribute("includingDocument", document); request.setAttribute("includedDocumentId", includedDocumentId); request.setAttribute("label", label); request.setAttribute("includeIndex", no); return Utility.getContents("/imcms/" + user.getLanguageIso639_2() + "/jsp/docadmin/text/edit_include.jsp", request, response); } catch (Exception e) { throw new UnhandledException(e); } } else if (parserParameters.getIncludeLevel() > 0) { if (null == includedDocumentId) { return ""; } ParserParameters includedDocumentParserParameters = createIncludedDocumentParserParameters(parserParameters, includedDocumentId, attributes); StringWriter writer = new StringWriter(); textDocParser.untimedParsePage(includedDocumentParserParameters, writer); PatternMatcher patMat = new Perl5Matcher(); String documentStr = Util.substitute(patMat, htmlPrebodyPattern, NULL_SUBSTITUTION, writer.toString()); documentStr = Util.substitute(patMat, htmlPostbodyPattern, NULL_SUBSTITUTION, documentStr); return documentStr; } else { return "<!-- imcms:include failed: max include-level reached. -->"; } } catch (IOException ex) { return "<!-- imcms:include failed: " + ex + " -->"; } }
private void removePhoneNumbers(UserDomainObject newUser) { String[] sprocParameters = new String[]{String.valueOf(newUser.getId())}; try { services.getProcedureExecutor().executeUpdateProcedure(SPROC_DEL_PHONE_NR, sprocParameters); } catch (DatabaseException e) { throw new UnhandledException(e); } }
/** * @deprecated */ public String[] getRoleNames(UserDomainObject user) { try { final Object[] parameters = new String[]{"" + user.getId()}; return services.getProcedureExecutor().executeProcedure(SPROC_GET_USER_ROLES, parameters, new StringArrayResultSetHandler()); } catch (DatabaseException e) { throw new UnhandledException(e); } }
public synchronized RoleDomainObject addRole(String roleName) { RoleDomainObject role = getRoleByName(roleName); if (null == role) { role = new RoleDomainObject(roleName); try { addRole(role); } catch (UserAndRoleRegistryException e) { throw new UnhandledException(e); } } return role; }
public void deleteRole(RoleDomainObject role) { if (null == role) { return; } try { DatabaseCommand databaseCommand = new CompositeDatabaseCommand(new DatabaseCommand[]{ new DeleteWhereColumnsEqualDatabaseCommand("roles_rights", "role_id", "" + role.getId()), new DeleteWhereColumnsEqualDatabaseCommand("user_roles_crossref", "role_id", "" + role.getId()), new DeleteWhereColumnsEqualDatabaseCommand("roles", "role_id", "" + role.getId()), }); services.getDatabase().execute(databaseCommand); } catch (DatabaseException e) { throw new UnhandledException(e); } }
private RoleDomainObject[] getRoles(String rolesSql) { try { final Object[] parameters = new String[0]; String[][] sqlRows = (String[][]) services.getDatabase().execute(new SqlQueryCommand(rolesSql, parameters, Utility.STRING_ARRAY_ARRAY_HANDLER)); RoleDomainObject[] roles = new RoleDomainObject[sqlRows.length]; for (int i = 0; i < sqlRows.length; i++) { roles[i] = getRoleFromSqlResult(sqlRows[i]); } return roles; } catch (DatabaseException e) { throw new UnhandledException(e); } }
public RoleDomainObject getRoleById(int roleId) { try { final Object[] parameters = new String[]{"" + roleId}; String[] sqlResult = (String[]) services.getDatabase().execute(new SqlQueryCommand(SQL_SELECT_ROLE_BY_ID, parameters, Utility.STRING_ARRAY_HANDLER)); return getRoleFromSqlResult(sqlResult); } catch (DatabaseException e) { throw new UnhandledException(e); } }
public RoleDomainObject getRoleByName(String wantedRoleName) { try { final Object[] parameters = new String[]{wantedRoleName}; String[] sqlResult = (String[]) services.getDatabase().execute(new SqlQueryCommand(SQL_SELECT_ROLE_BY_NAME, parameters, Utility.STRING_ARRAY_HANDLER)); return getRoleFromSqlResult(sqlResult); } catch (DatabaseException e) { throw new UnhandledException(e); } }
private void saveExistingRole(RoleDomainObject role) { int unionOfRolePermissionIds = getUnionOfRolePermissionIds(role); try { final Object[] parameters = new String[]{ role.getName(), "" + unionOfRolePermissionIds, "" + role.getId()}; services.getDatabase().execute(new SqlUpdateCommand("UPDATE roles SET role_name = ?, permissions = ? WHERE role_id = ?", parameters)); } catch (DatabaseException e) { throw new UnhandledException(e); } }
private Date getSessionCounterDateFromDb() { try { DateFormat dateFormat = new SimpleDateFormat(DateConstants.DATE_FORMAT_STRING); final Object[] parameters = new String[0]; return dateFormat.parse((String) getDatabase().execute(new SqlQueryCommand("SELECT value FROM sys_data WHERE type_id = 2", parameters, Utility.SINGLE_STRING_HANDLER))); } catch (ParseException ex) { log.fatal("Failed to get SessionCounterDate from db.", ex); throw new UnhandledException(ex); } }
private String getTemplate(String path, UserDomainObject user, List<String> variables) { try { VelocityEngine velocity = getVelocityEngine(user); VelocityContext context = getVelocityContext(user); if (null != variables) { List<String> parseDocVariables = new ArrayList<>(variables.size()); for (Iterator<String> iterator = variables.iterator(); iterator.hasNext(); ) { String key = iterator.next(); String value = iterator.next(); context.put(key, value); boolean isVelocityVariable = StringUtils.isAlpha(key) || !(value != null); if (!isVelocityVariable) { parseDocVariables.add(key); parseDocVariables.add(value); } } variables = parseDocVariables; } StringWriter stringWriter = new StringWriter(); velocity.mergeTemplate(path, Imcms.DEFAULT_ENCODING, context, stringWriter); String result = stringWriter.toString(); if (null != variables) { result = Parser.parseDoc(result, variables.toArray(new String[variables.size()])); } return result; } catch (Exception e) { throw new UnhandledException("getTemplate(\"" + path + "\") : " + e.getMessage(), e); } }
public VelocityEngine getVelocityEngine(UserDomainObject user) { try { String languageIso639_2 = user.getLanguageIso639_2(); VelocityEngine velocityEngine = velocityEngines.get(languageIso639_2); if (velocityEngine == null) { velocityEngine = createVelocityEngine(languageIso639_2); velocityEngines.put(languageIso639_2, velocityEngine); } return velocityEngine; } catch (Exception e) { throw new UnhandledException(e); } }
/** * @param file file to clone * @return file clone or null if provided file is null */ private FileDocumentFile cloneFile(FileDocumentFile file) { if (null == file) { return null; } FileDocumentFile fileClone; try { fileClone = file.clone(); } catch (CloneNotSupportedException e) { throw new UnhandledException(e); } return fileClone; }
public XmlDocumentBuilder(UserDomainObject user) { currentUser = user; try { xmlDocument = createXmlDocument(); Element imcmsElement = xmlDocument.createElement("imcms"); documentsElement = xmlDocument.createElement("documents"); imcmsElement.appendChild(documentsElement); xmlDocument.appendChild(imcmsElement); } catch (ParserConfigurationException e) { throw new UnhandledException(e); } }
public String toString() { try { servletOutputStream.flush(); byteArrayOutputStream.flush(); printWriter.flush(); stringWriter.flush(); if (byteArrayOutputStream.size() > 0) { return byteArrayOutputStream.toString(Imcms.DEFAULT_ENCODING); } else { return stringWriter.toString(); } } catch (IOException e) { throw new UnhandledException(e); } }
/** * Returns the menubuttonrow */ public static String getAdminButtons(UserDomainObject user, DocumentDomainObject document, HttpServletRequest request, HttpServletResponse response) { if (null == document || !(user.canEdit(document) || user.isUserAdminAndCanEditAtLeastOneRole() || user.canAccessAdminPages())) { return ""; } try { request.setAttribute("document", document); request.setAttribute("user", user); return Utility.getContents("/imcms/" + user.getLanguageIso639_2() + "/jsp/admin/admin_panel.jsp", request, response); } catch (ServletException | IOException e) { throw new UnhandledException(e); } }
public static void writeXmlDocument(Document xmlDocument, StreamResult streamResult) { try { TransformerFactory transformerFactory = TransformerFactory.newInstance(); javax.xml.transform.Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); DOMSource xmlSource = new DOMSource(xmlDocument); transformer.transform(xmlSource, streamResult); } catch (TransformerException e) { throw new UnhandledException(e); } }
public Mail(String fromAddress) { try { mail.setFrom(fromAddress); } catch (EmailException e) { LocalizedMessage errorMessage = new LocalizedMessage("error/missing_email_fromAdress"); throw new UnhandledException(errorMessage.toLocalizedString("eng"), e); } }
public void setBccAddresses(String[] bccAddresses) { try { mail.setBcc(CollectionUtils.collect(Arrays.asList(bccAddresses), new StringToInternetAddressTransformer())); } catch (EmailException e) { throw new UnhandledException(e); } }