List of usage examples for java.lang SecurityException SecurityException
public SecurityException(Throwable cause)
From source file:org.fao.geonet.api.records.MetadataWorkflowApi.java
@ApiOperation(value = "Set the record status", notes = "", nickname = "setStatus") @RequestMapping(value = "/{metadataUuid}/status", method = RequestMethod.PUT) @PreAuthorize("hasRole('Editor')") @ApiResponses(value = { @ApiResponse(code = 204, message = "Status updated."), @ApiResponse(code = 403, message = ApiParams.API_RESPONSE_NOT_ALLOWED_CAN_EDIT) }) @ResponseStatus(HttpStatus.NO_CONTENT)/*from w w w . j a v a 2 s .co m*/ public void setStatus( @ApiParam(value = API_PARAM_RECORD_UUID, required = true) @PathVariable String metadataUuid, @ApiParam(value = "Metadata status", required = true) @RequestBody(required = true) MetadataStatusParameter status, HttpServletRequest request) throws Exception { AbstractMetadata metadata = ApiUtils.canEditRecord(metadataUuid, request); ApplicationContext appContext = ApplicationContextHolder.get(); ServiceContext context = ApiUtils.createServiceContext(request, languageUtils.getIso3langCode(request.getLocales())); AccessManager am = appContext.getBean(AccessManager.class); //--- only allow the owner of the record to set its status if (!am.isOwner(context, String.valueOf(metadata.getId()))) { throw new SecurityException(String.format( "Only the owner of the metadata can set the status of this record. User is not the owner of the metadata.")); } //--- use StatusActionsFactory and StatusActions class to //--- change status and carry out behaviours for status changes StatusActionsFactory saf = appContext.getBean(StatusActionsFactory.class); StatusActions sa = saf.createStatusActions(context); int author = context.getUserSession().getUserIdAsInt(); MetadataStatus metadataStatus = convertParameter(metadata.getId(), status, author); List<MetadataStatus> listOfStatusChange = new ArrayList<>(1); listOfStatusChange.add(metadataStatus); sa.onStatusChange(listOfStatusChange); //--- reindex metadata DataManager dataManager = appContext.getBean(DataManager.class); dataManager.indexMetadata(String.valueOf(metadata.getId()), true, null); }
From source file:de.juwimm.cms.authorization.remote.AuthorizationServiceSpringImpl.java
@Override protected void handleRemoteLoginLive(String userName, String pass) throws Exception { UserHbm user;/*from ww w .j ava2s . c om*/ try { user = getUserHbmDao().load(userName); } catch (Exception ex) { throw new SecurityException("Invalid Principal"); } user.setLoginDate((System.currentTimeMillis())); LoginContext lc = new LoginContext("juwimm-cms-security-domain", new CredentialCallbackHandler(userName, pass)); lc.login(); //UserLoginValue ulv = getUserHbmDao().getUserLoginValue(user); //return ulv; }
From source file:org.kawanfw.sql.servlet.sql.ServerStatement.java
/** * Execute the passed SQL Statement and return: <br> * - The result set as a List of Maps for SELECT statements. <br> * - The return code for other statements * // ww w .j ava2 s. co m * @param sqlOrder * the qsql order * @param sqlParms * the sql parameters * @param out * the output stream where to write to result set output * * * @throws SQLException */ private void executeQueryOrUpdatePrepStatement(OutputStream out) throws SQLException, IOException { String sqlOrder = statementHolder.getSqlOrder(); debug("statementHolder: " + statementHolder.getSqlOrder()); debug("sqlOrder : " + sqlOrder); // sqlOrder = HtmlConverter.fromHtml(sqlOrder); if (statementHolder.isDoExtractResultSetMetaData()) { sqlOrder = DbVendorManager.addLimit1(sqlOrder, connection); } PreparedStatement preparedStatement = null; boolean usesAutoGeneratedKeys = false; if (statementHolder.getAutoGeneratedKeys() != -1) { preparedStatement = connection.prepareStatement(sqlOrder, statementHolder.getAutoGeneratedKeys()); usesAutoGeneratedKeys = true; } else if (statementHolder.getColumnIndexesAutogenerateKeys().length != 0) { preparedStatement = connection.prepareStatement(sqlOrder, statementHolder.getColumnIndexesAutogenerateKeys()); usesAutoGeneratedKeys = true; } else if (statementHolder.getColumnNamesAutogenerateKeys().length != 0) { preparedStatement = connection.prepareStatement(sqlOrder, statementHolder.getColumnNamesAutogenerateKeys()); usesAutoGeneratedKeys = true; } else { preparedStatement = connection.prepareStatement(sqlOrder); } Map<Integer, Integer> parameterTypes = null; Map<Integer, String> parameterStringValues = null; // Class to set all the statement parameters ServerPreparedStatementParameters serverPreparedStatementParameters = null; try { ServerSqlUtil.setStatementProperties(preparedStatement, statementHolder); parameterTypes = statementHolder.getParameterTypes(); parameterStringValues = statementHolder.getParameterStringValues(); debug("before ServerPreparedStatementParameters"); serverPreparedStatementParameters = new ServerPreparedStatementParameters(request, username, fileConfigurator, preparedStatement, statementHolder); serverPreparedStatementParameters.setParameters(); // Throws a SQL exception if the order is not authorized: debug("before new SqlSecurityChecker()"); boolean isAllowedAfterAnalysis = sqlConfigurator.allowStatementAfterAnalysis(username, connection, sqlOrder, serverPreparedStatementParameters.getParameterValues()); if (!isAllowedAfterAnalysis) { String ipAddress = request.getRemoteAddr(); SqlConfiguratorCall.runIfStatementRefused(sqlConfigurator, username, connection, ipAddress, sqlOrder, serverPreparedStatementParameters.getParameterValues()); debug("Before SqlConfiguratorCall.runIfStatementRefused"); SqlConfiguratorCall.runIfStatementRefused(sqlConfigurator, ipAddress, connection, ipAddress, sqlOrder, serverPreparedStatementParameters.getParameterValues()); debug("After SqlConfiguratorCall.runIfStatementRefused"); String message = Tag.PRODUCT_SECURITY + " [" + "{Prepared Statement not authorized}" + "{sql order : " + sqlOrder + "}" + "{sql parms : " + parameterTypes + "}" + "{sql values: " + parameterStringValues + "}]"; throw new SecurityException(message); } isAllowedAfterAnalysis = SqlConfiguratorCall.allowResultSetGetMetaData(sqlConfigurator, username, connection); if (statementHolder.isDoExtractResultSetMetaData() && !isAllowedAfterAnalysis) { String message = Tag.PRODUCT_SECURITY + " ResultSet.getMetaData() Query not authorized."; throw new SecurityException(message); } debug("before executeQuery() / executeUpdate()"); if (statementHolder.isExecuteUpdate()) { if (!SqlConfiguratorCall.allowExecuteUpdate(sqlConfigurator, username, connection)) { String ipAddress = request.getRemoteAddr(); SqlConfiguratorCall.runIfStatementRefused(sqlConfigurator, username, connection, ipAddress, sqlOrder, serverPreparedStatementParameters.getParameterValues()); String message = Tag.PRODUCT_SECURITY + " [" + "{Prepared Statement not authorized for executeUpdate}" + "{sql order : " + sqlOrder + "}" + "{sql parms : " + parameterTypes + "}" + "{sql values: " + parameterStringValues + "}]"; throw new SecurityException(message); } int rc = preparedStatement.executeUpdate(); //br.write(TransferStatus.SEND_OK + CR_LF); //br.write(rc + CR_LF); ServerSqlManager.writeLine(out, TransferStatus.SEND_OK); ServerSqlManager.writeLine(out, "" + rc); // Write the preparedStatement.getGeneratedKeys() on the stream // if necessary if (usesAutoGeneratedKeys) { ResultSet rs = null; try { rs = preparedStatement.getGeneratedKeys(); ResultSetWriter resultSetWriter = new ResultSetWriter(request, out, commonsConfigurator, fileConfigurator, sqlConfigurator, username, sqlOrder, statementHolder); resultSetWriter.write(rs); } finally { if (rs != null) { rs.close(); } } } } else { ResultSet rs = null; try { if (statementHolder.isDoExtractResultSetMetaData()) { preparedStatement.setMaxRows(1); } else { ServerSqlUtil.setMaxRowsToReturn(preparedStatement, sqlConfigurator); } rs = preparedStatement.executeQuery(); //br.write(TransferStatus.SEND_OK + CR_LF); ServerSqlManager.writeLine(out, TransferStatus.SEND_OK); // If a a ResultSet.getMetaData() has been asked, send it // back! if (statementHolder.isDoExtractResultSetMetaData()) { ResultSetMetaDataWriter resultSetMetaDataWriter = new ResultSetMetaDataWriter(out, commonsConfigurator, sqlConfigurator); resultSetMetaDataWriter.write(rs); } else { // print(rs, br); ResultSetWriter resultSetWriter = new ResultSetWriter(request, out, commonsConfigurator, fileConfigurator, sqlConfigurator, username, sqlOrder, statementHolder); resultSetWriter.write(rs); } } finally { if (rs != null) { rs.close(); } } } } catch (SQLException e) { ServerLogger.getLogger().log(Level.WARNING, Tag.PRODUCT_EXCEPTION_RAISED + CR_LF + "Prepared statement: " + sqlOrder + CR_LF + "- sql order : " + sqlOrder + CR_LF + "- sql parms : " + parameterTypes + CR_LF + "- sql values: " + parameterStringValues + CR_LF + "- exception : " + e.toString()); throw e; } finally { // Close the ServerPreparedStatementParameters if (serverPreparedStatementParameters != null) { serverPreparedStatementParameters.close(); } if (preparedStatement != null) { preparedStatement.close(); } // Clean all parameterTypes = null; parameterStringValues = null; serverPreparedStatementParameters = null; } }
From source file:net.es.netshell.kernel.users.Users.java
@SysCall(name = "do_createUser") public void do_createUser(UserProfile newUser, boolean createContainer) throws UserAlreadyExistException, UserException, UserClassException, IOException { logger.info("do_createUser entry"); if (BootStrap.getBootStrap().isStandAlone()) { throw new SecurityException("not allowed"); }//from w w w . j a va 2 s .co m String username = newUser.getName(); String password = newUser.getPassword(); String privilege = newUser.getPrivilege(); String name = newUser.getRealName(); String organization = newUser.getorganization(); String email = newUser.getemail(); // Check if fields entered contain valid characters (and don't contain colons) /* lomax@es.net: disabling this test in order to allow users to be the name of containers, or email address. * not sure if the test is really needed anyway. * todo Revisit: dhua@es.net->lomax@es.net: if we want to be safe, we should still check if any field contains a colon (since that's how our password file fields are delimited) * Username check was needed because some symbols may be invalid on certain file systems (colon, semicolon, pipe, comma, slash, etc --esp in Windows), and the directory name is created from username * if (! username.matches("[a-zA-Z0-9_/]+") || name.contains(":") || organization.contains(":") || email.contains(":") || ! email.contains("@") || ! email.contains(".")) { throw new UserException(username); } **/ // Make sure privilege value entered is valid if (!privArray.contains(privilege)) { throw new UserClassException(privilege); } // Checks if the user already exists try { this.readUserFile(); } catch (IOException e) { logger.error("Cannot read password file"); } if (this.passwords.containsKey(username)) { throw new UserAlreadyExistException(username); } // Construct the new Profile. A null, empty or * password means that password is disabled for the user. UserProfile userProfile = new UserProfile(username, (password != null) && (!password.equals("") && (!password.equals("*"))) ? crypt(password) : // Let the Crypt library pick a suitable algorithm and a random salt "*", privilege, name, organization, email); this.passwords.put(username, userProfile); // Create home directory File homeDir = new File(Paths.get(this.getHomePath().toString(), username).toString()); homeDir.mkdirs(); // Create proper access right FileACL fileACL = new FileACL(homeDir.toPath()); fileACL.allowUserRead(username); fileACL.allowUserWrite(username); // Commit ACL's fileACL.store(); // Update NetShell user file this.writeUserFile(); }
From source file:org.onecmdb.core.utils.wsdl.OneCMDBWebServiceImpl.java
public CiBean[] evalRelation(String auth, CiBean source, String relationPath, QueryCriteria crit) { long start = System.currentTimeMillis(); log.info("WSDL: evalRelation(" + auth + ", " + relationPath + ")"); // Update all beans. ISession session = onecmdb.getSession(auth); if (session == null) { throw new SecurityException("No Session found! Try to do auth() first!"); }//w w w.j av a 2 s. c om if (source == null) { throw new IllegalArgumentException("Source can not be null!"); } IModelService modelSvc = (IModelService) session.getService(IModelService.class); ICi ci = null; if (source.getId() != null) { ci = modelSvc.find(new ItemId(source.getId())); if (ci == null) { throw new IllegalArgumentException("CI with id <" + source.getId() + "> not found"); } } else if (source.getAlias() != null) { ci = modelSvc.findCi(new Path<String>(source.getAlias())); if (ci == null) { throw new IllegalArgumentException("CI with alias <" + source.getAlias() + "> not found"); } } if (ci == null) { throw new IllegalArgumentException("Source CI have no id or alias specified!"); } // Lookup the source OnecmdbUtils utils = new OnecmdbUtils(session); //Set<IValue> set = utils.evaluate(ci, relationPath); QueryResult result = utils.evaluate(ci, relationPath, crit, false); // Convert Values to Beans. long stop = System.currentTimeMillis(); log.info("WSDL: evalRelation completed in " + (stop - start) + "ms returned + " + result.size() + " objects"); start = stop; ArrayList<CiBean> resultList = new ArrayList<CiBean>(); OneCmdbBeanProvider converter = new OneCmdbBeanProvider(); for (Object resCI : result) { if (resCI instanceof ICi) { // Convert ci to cibean. CiBean bean = converter.convertCiToBean((ICi) resCI); resultList.add(bean); } } stop = System.currentTimeMillis(); log.info("WSDL: evalRelation convert completed in " + (stop - start) + "ms returned + " + resultList.size() + " beans"); return (resultList.toArray(new CiBean[0])); }
From source file:org.sakaiproject.iclicker.tool.ToolController.java
public void processAdmin(PageContext pageContext, HttpServletRequest request) { // admin check if (!this.isAdmin()) { throw new SecurityException("Current user is not an admin and cannot access the admin view"); }/* ww w . j a v a2 s .c om*/ int pageNum = 1; int perPageNum = 20; // does not change if ((request.getParameter("page") != null)) { try { pageNum = Integer.parseInt(request.getParameter("page")); if (pageNum < 1) { pageNum = 1; } } catch (NumberFormatException e) { // nothing to do System.err.println("WARN: invalid page number: " + request.getParameter("page") + ":" + e); } } pageContext.setAttribute("page", pageNum); pageContext.setAttribute("perPage", perPageNum); String sort = "clickerId"; if ((request.getParameter("sort") != null)) { sort = request.getParameter("sort"); } pageContext.setAttribute("sort", sort); if ("POST".equalsIgnoreCase(request.getMethod())) { if ((request.getParameter("activate") != null)) { // First arrived at this page boolean activate = Boolean.parseBoolean(request.getParameter("activate")); if ((request.getParameter("registrationId") == null)) { ToolController.addMessage(pageContext, ToolController.KEY_ERROR, "reg.activate.registrationId.empty", (Object[]) null); } else { try { Long registrationId = Long.parseLong(request.getParameter("registrationId")); // save a new clicker registration ClickerRegistration cr = this.getLogic().setRegistrationActive(registrationId, activate); if (cr != null) { ToolController.addMessage(pageContext, ToolController.KEY_INFO, "admin.activate.success." + cr.isActivated(), cr.getClickerId(), this.getLogic().getUserDisplayName(cr.getOwnerId())); } } catch (NumberFormatException e) { ToolController.addMessage(pageContext, ToolController.KEY_ERROR, "reg.activate.registrationId.nonnumeric", request.getParameter("registrationId")); } } } else if ((request.getParameter("remove") != null)) { if ((request.getParameter("registrationId") == null)) { ToolController.addMessage(pageContext, ToolController.KEY_ERROR, "reg.activate.registrationId.empty", (Object[]) null); } else { try { Long registrationId = Long.parseLong(request.getParameter("registrationId")); ClickerRegistration cr = this.getLogic().getItemById(registrationId); if (cr != null) { this.getLogic().removeItem(cr); ToolController.addMessage(pageContext, ToolController.KEY_INFO, "admin.delete.success", cr.getClickerId(), registrationId, this.getLogic().getUserDisplayName(cr.getOwnerId())); } } catch (NumberFormatException e) { ToolController.addMessage(pageContext, ToolController.KEY_ERROR, "reg.activate.registrationId.nonnumeric", request.getParameter("registrationId")); } } } else if ((request.getParameter("runner") != null)) { // initiate the runner process String runnerType; if ((request.getParameter("addAll") != null)) { runnerType = BigRunner.RUNNER_TYPE_ADD; } else if ((request.getParameter("removeAll") != null)) { runnerType = BigRunner.RUNNER_TYPE_REMOVE; } else if ((request.getParameter("syncAll") != null)) { runnerType = BigRunner.RUNNER_TYPE_SYNC; } else { throw new IllegalArgumentException("Invalid request type: missing valid parameter"); } try { logic.startRunnerOperation(runnerType); String msgKey = "admin.process.message." + runnerType; ToolController.addMessage(pageContext, ToolController.KEY_INFO, msgKey, (Object[]) null); } catch (ClickerLockException e) { ToolController.addMessage(pageContext, ToolController.KEY_ERROR, "admin.process.message.locked", runnerType); } catch (IllegalStateException e) { ToolController.addMessage(pageContext, ToolController.KEY_ERROR, "admin.process.message.locked", runnerType); } } else { // invalid POST System.err .println("WARN: Invalid POST: does not contain runner, remove, or activate, nothing to do"); } } // put config data into page pageContext.setAttribute("ssoEnabled", logic.isSingleSignOnEnabled()); if (logic.isSingleSignOnEnabled()) { pageContext.setAttribute("ssoSharedKey", logic.getSharedKey()); } pageContext.setAttribute("domainURL", logic.domainURL); pageContext.setAttribute("workspacePageTitle", logic.workspacePageTitle); // put error data into page pageContext.setAttribute("recentFailures", logic.getFailures()); // put runner status in page makeRunnerStatus(pageContext, true); // handling the calcs for paging int first = (pageNum - 1) * perPageNum; int totalCount = this.getLogic().countAllItems(); int pageCount = (totalCount + perPageNum - 1) / perPageNum; pageContext.setAttribute("totalCount", totalCount); pageContext.setAttribute("pageCount", pageCount); pageContext.setAttribute("registrations", this.getLogic().getAllItems(first, perPageNum, sort, null, true)); if (totalCount > 0) { StringBuilder sb = new StringBuilder(); Date d = new Date(); for (int i = 0; i < pageCount; i++) { int currentPage = i + 1; int currentStart = (i * perPageNum) + 1; int currentEnd = currentStart + perPageNum - 1; if (currentEnd > totalCount) { currentEnd = totalCount; } String marker = "[" + currentStart + ".." + currentEnd + "]"; if (currentPage == pageNum) { // make it bold and not a link sb.append("<span class=\"paging_current paging_item\">").append(marker).append("</span>\n"); } else { // make it a link sb.append("<a class=\"paging_link paging_item\" href=\"") .append(pageContext.findAttribute("adminPath")).append("&page=").append(currentPage) .append("&sort=").append(sort).append("&nc=").append(d.getTime() + currentPage) .append("\">").append(marker).append("</a>\n"); } } pageContext.setAttribute("pagerHTML", sb.toString()); } }
From source file:de.juwimm.cms.authorization.remote.AuthorizationServiceSpringImpl.java
@Override protected UserLoginValue handleRemoteLogin(String userName, String pass) throws Exception { UserHbm user;/*www . j av a 2s .c o m*/ try { user = getUserHbmDao().load(userName); } catch (Exception ex) { throw new SecurityException("Invalid Principal"); } user.setLoginDate((System.currentTimeMillis())); LoginContext lc = new LoginContext("juwimm-cms-security-domain", new CredentialCallbackHandler(userName, pass)); lc.login(); UserLoginValue ulv = getUserHbmDao().getUserLoginValue(user); return ulv; }
From source file:de.juwimm.cms.remote.UserServiceSpringImpl.java
/** * Removes some ViewComponents from this Task. * /*from ww w . j a va2 s .co m*/ * @param taskId * TaskId of the related Task * @param vcIds * Integer Array of ViewComponents to remove. * * @see de.juwimm.cms.remote.UserServiceSpring#removeViewComponentsFromTask(java.lang.Integer, * java.lang.Integer[]) */ @Override protected void handleRemoveViewComponentsFromTask(Integer taskId, Integer[] vcIds) throws Exception { UserHbm user = null; TaskHbm task = null; try { user = super.getUserHbmDao().load(AuthenticationHelper.getUserName()); task = super.getTaskHbmDao().load(taskId); if (task != null) { if (!!getUserHbmDao().isInRole(user, UserRights.SITE_ROOT, user.getActiveSite()) && !user.equals(task.getReceiver()) && !user.equals(task.getSender()) && !!getUserHbmDao().isInRole(user, task.getReceiverRole(), user.getActiveSite())) { throw new SecurityException("User is not responsible to change this Task. RECEIVER:" + task.getReceiver() + " SENDER:" + task.getSender() + " RECEIVERROLE:" + task.getReceiverRole() + " THIS USER:" + user.getUserId()); } try { Collection<ViewComponentHbm> coll = task.getViewComponents(); for (int i = 0; i < vcIds.length; i++) { ViewComponentHbm vc = super.getViewComponentHbmDao().load(vcIds[i]); coll.remove(vc); } task.setViewComponents(coll); } catch (Exception exe) { log.error("Error occured", exe); } } else { log.warn("Task with Id " + taskId + " was not found"); } } catch (Exception e) { throw new UserException(e.getMessage()); } }
From source file:com.glaf.core.security.SecurityUtils.java
/** * /*from w w w. ja v a 2s. com*/ * * @param ctx * * @param content * * @param key * * @return byte[] ? */ public static byte[] symmetryEncrypt(SecurityContext ctx, byte[] content, Key key) { try { byte[] cipherContent = null; Cipher cipher = Cipher.getInstance(ctx.getSymmetryAlgorithm(), ctx.getJceProvider()); SecureRandom secureRandom = SecureRandom.getInstance(ctx.getSecureRandomAlgorithm()); cipher.init(Cipher.ENCRYPT_MODE, key, secureRandom); cipherContent = cipher.doFinal(content); return cipherContent; } catch (Exception ex) { throw new SecurityException(ex); } }
From source file:com.gsma.rcs.provisioning.local.Provisioning.java
private String[] getProvisioningFiles() { if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE }, MY_PERMISSION_REQUEST_ALL); throw new SecurityException("Permission not granted to access SD card!"); }/* ww w .j av a 2 s.c o m*/ String[] files = null; File folder = new File(PROVISIONING_FOLDER_PATH); // noinspection ResultOfMethodCallIgnored folder.mkdirs(); if (folder.exists()) { // filter FilenameFilter filter = new FilenameFilter() { public boolean accept(File dir, String filename) { return filename.endsWith(PROVISIONING_EXTENSION); } }; files = folder.list(filter); } if (files == null || files.length == 0) { // No provisioning file return new String[] { getString(R.string.label_no_xml_file) }; } return files; }