Java Code Examples for javax.faces.application.FacesMessage

The following examples show how to use javax.faces.application.FacesMessage. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: development   Source File: ParameterValueValidator.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Validate integer value.
 * 
 * @param context
 *            JSF context.
 * @param uiComponent
 *            UI component.
 * @param value
 *            Value for validation.
 */
private void validateInteger(FacesContext context, UIComponent uiComponent,
        String value) {
    if (!GenericValidator.isInt(value.toString())) {
        Object[] args = null;
        String label = JSFUtils.getLabel(uiComponent);
        if (label != null) {
            args = new Object[] { label };
        }
        ValidationException e = new ValidationException(
                ValidationException.ReasonEnum.INTEGER, label, null);
        String text = JSFUtils.getText(e.getMessageKey(), args, context);
        throw new ValidatorException(new FacesMessage(
                FacesMessage.SEVERITY_ERROR, text, null));
    }
}
 
Example 2
Source Project: development   Source File: OperatorOrgBean.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * This functions persists the changed data of the currently selected
 * organization.
 * 
 * @return <code>OUTCOME_SUCCESS</code> if the organization was successfully
 *         updated.
 * 
 * @throws SaaSApplicationException
 *             if any problems occurs while persisting the values
 * @throws ImageException
 *             Thrown in case the access to the uploaded file failed.
 */
public String saveOrganization() throws SaaSApplicationException {

    OperatorService operatorService = getOperatorService();
    VOOperatorOrganization org = getSelectedOrganization();

    long updatedTenantKey = selectedOrganization.getTenantKey();

    manageTenantService.validateOrgUsersUniqnessInTenant(
            org.getOrganizationId(), updatedTenantKey);

    selectedOrganization = operatorService.updateOrganization(org,
            getImageUploader().getVOImageResource());

    addMessage(null, FacesMessage.SEVERITY_INFO, INFO_ORGANIZATION_SAVED,
            selectedOrganization.getOrganizationId());

    // make sure the next page access will trigger the reload of the
    // selected organization the next time getSelectedOrg will be called
    this.selectedOrganization = null;
    selectedPSPAccounts = null;

    return OUTCOME_SUCCESS;
}
 
Example 3
/**
 * This listener will read in the instructions, parse any variables and 
 * formula names it finds, and then check to see if there are any errors 
 * in the configuration for the question.  
 * 
 * <p>Errors include <ul><li>no variables or formulas named in the instructions</li>
 * <li>variables and formulas sharing a name</li>
 * <li>variables with invalid ranges of values</li>
 * <li>formulas that are syntactically wrong</li></ul>
 * Any errors are written to the context messager
 * <p>The validate formula is also called directly from the ItemAddListner, before
 * saving a calculated question, to ensure any last minute changes are caught.
 */
public void processAction(ActionEvent arg0) throws AbortProcessingException {
    ItemAuthorBean itemauthorbean = (ItemAuthorBean) ContextUtil.lookupBean("itemauthor");
    ItemBean item = itemauthorbean.getCurrentItem();
            
    List<String> errors = this.validate(item,true);        
    
    if (errors.size() > 0) {
        item.setOutcome("calculatedQuestion");
        item.setPoolOutcome("calculatedQuestion");
        FacesContext context=FacesContext.getCurrentInstance();
        for (String error : errors) {
            context.addMessage(null, new FacesMessage(error));
        }
        context.renderResponse();                         
    }
}
 
Example 4
Source Project: development   Source File: TechServiceBean.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Delete the selected technical service.
 * 
 * @return the logical outcome.
 * @throws SaaSApplicationException
 */
public String delete() throws SaaSApplicationException {

    if (isTokenValid()) {
        if (selectedTechnicalService != null) {
            try {
                getProvisioningService().deleteTechnicalService(
                        selectedTechnicalService.getVo());
                sessionBean.setSelectedTechnicalServiceKey(0);
                addMessage(null, FacesMessage.SEVERITY_INFO,
                        INFO_TECH_SERVICE_DELETED,
                        new Object[] { selectedTechnicalService
                                .getTechnicalServiceId() });
            } finally {
                selectedTechnicalService = null;
                technicalServices = null;
            }
        }
        resetToken();
    }

    return OUTCOME_SUCCESS;
}
 
Example 5
Source Project: ee8-sandbox   Source File: MessageHandler.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Remove the messages that are not associated with any particular component
 * from the user's session and add them to the faces context.
 *
 * @return the number of removed messages.
 */
private int restoreMessages(FacesContext facesContext) {
	// remove messages from the session
	Map<String, Object> sessionMap = facesContext.getExternalContext().getSessionMap();
	@SuppressWarnings("unchecked")
	List<FacesMessage> messages = (List<FacesMessage>)sessionMap.remove(sessionToken);
	// store them in the context
	if(messages == null) {
		return 0;
	}
	int restoredCount = messages.size();
	for(Iterator<FacesMessage> i = messages.iterator(); i.hasNext(); ) {
		facesContext.addMessage(null, i.next());
	}

	return restoredCount;
}
 
Example 6
public void processAction(ActionEvent ae) throws AbortProcessingException
 {
AssessmentBean assessmentBean = (AssessmentBean) ContextUtil.lookupBean("assessmentBean");

AuthorizationBean authzBean = (AuthorizationBean) ContextUtil.lookupBean("authorization");
AuthorBean authorBean = (AuthorBean) ContextUtil.lookupBean("author");

if (!authzBean.isUserAllowedToEditAssessment(assessmentBean.getAssessmentId(), assessmentBean.getAssessment().getCreatedBy(),
		!authorBean.getIsEditPendingAssessmentFlow()))
{
	FacesContext context = FacesContext.getCurrentInstance();
	String err = ContextUtil.getLocalizedString("org.sakaiproject.tool.assessment.bundle.AuthorMessages", "denied_edit_assessment_error");
	context.addMessage(null, new FacesMessage(err));
	return;
}

assessmentBean.setQuestionSizeAndTotalScore();
 }
 
Example 7
Source Project: BootsFaces-OSP   Source File: Tooltip.java    License: Apache License 2.0 6 votes vote down vote up
private static void verifyAndWriteTooltip(FacesContext context, ResponseWriter rw, String tooltip,
		String position, String container) throws IOException {
	if (null == position)
		position="bottom";
	boolean ok = "top".equals(position);
	ok |= "bottom".equals(position);
	ok |= "right".equals(position);
	ok |= "left".equals(position);
	ok |= "auto".equals(position);
	ok |= "auto top".equals(position);
	ok |= "auto bottom".equals(position);
	ok |= "auto right".equals(position);
	ok |= "auto left".equals(position);
	if (!ok) {
		position = "bottom";
		context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Wrong JSF markup",
				"Tooltip position must either be 'auto', 'top', 'bottom', 'left' or 'right'."));
	}
	rw.writeAttribute("data-toggle", "tooltip", null);
	rw.writeAttribute("data-placement", position, "data-placement");
	rw.writeAttribute("data-container", container, "data-container");
	rw.writeAttribute("title", tooltip, null);
}
 
Example 8
Source Project: ipst   Source File: EquipmentController.java    License: Mozilla Public License 2.0 6 votes vote down vote up
public String edit(Equipment eq) {
    log.log(Level.INFO, " edit enter:: [" + eq.getCimId() + "]");
    this.cimId = eq.getCimId();
    FacesContext context = FacesContext.getCurrentInstance();
    ResourceBundle bundle = context.getApplication().getResourceBundle(context, "msg");
    this.newEquipment = pmanager.findEquipment(eq.getCimId());
    try {
        if (newEquipment != null) {
            log.log(Level.INFO, "Edit Equipment : [" + newEquipment.getCimId() + "]");
            this.buildConnectionTable();
            return "edit?faces-redirect=true&includeViewParams=true";
        } else {
            throw new Exception("Edit: Equipment not found!");
        }
    } catch (Exception e) {
        log.log(Level.WARNING, "edit equipment:: catch an Exception" + e.getMessage());
        String errorMessage = getRootErrorMessage(e);
        FacesMessage m = new FacesMessage(FacesMessage.SEVERITY_ERROR, errorMessage, bundle.getString("edit.failure.msg"));
        facesContext.addMessage(null, m);
        return "edit";
    }
}
 
Example 9
Source Project: ipst   Source File: ModelTemplateController.java    License: Mozilla Public License 2.0 6 votes vote down vote up
public void updateMT() {
    log.log(Level.INFO, "update: [ id: " + this.modelTemplate.getId() + " "    + " comment: " + this.modelTemplate.getComment() + "]");
    FacesContext context = FacesContext.getCurrentInstance();
    ResourceBundle bundle = context.getApplication().getResourceBundle(context, "msg");
    try {
        updateModelTemplates();
        FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_INFO, this.modelTemplate.getComment() + "  " + bundle.getString("update.operation.msg"), bundle.getString("update.success.msg"));
        FacesContext.getCurrentInstance().addMessage(null, msg);

    } catch (Exception ex) {
        String errorMessage = getRootErrorMessage(ex);
        log.log(Level.WARNING, "Error  " + errorMessage);
        FacesMessage m = new FacesMessage(FacesMessage.SEVERITY_ERROR,    errorMessage, bundle.getString("update.failure.msg"));
        facesContext.addMessage(null, m);
    }

}
 
Example 10
Source Project: development   Source File: ExternalServicePriceModelCtrl.java    License: Apache License 2.0 6 votes vote down vote up
public void upload(VOServiceDetails service) {
    try {
        PriceModel priceModel = getExternalPriceModelService()
                .getExternalPriceModelForService(service);
        if (priceModel == null) {
            throw new ExternalPriceModelException();
        }
        loadPriceModelContent(priceModel);

        addMessage(null, FacesMessage.SEVERITY_INFO,
                INFO_EXTERNAL_PRICE_UPLOADED);
    } catch (ExternalPriceModelException e) {
        addMessage(null, FacesMessage.SEVERITY_ERROR,
                ERROR_EXTERNAL_PRICEMODEL_NOT_AVAILABLE);
    }
}
 
Example 11
Source Project: sailfish-core   Source File: TestScriptsBean.java    License: Apache License 2.0 6 votes vote down vote up
public void handleFileUpload(FileUploadEvent event) {

		logger.debug("Upload invoked {}", BeanUtil.getUser());

		UploadedFile uploadedFile = event.getFile() ;

		try {
			BeanUtil.getSfContext().getMatrixStorage().addMatrix(uploadedFile.getInputstream(), uploadedFile.getFileName(), null, "Unknown creator", null, null, null);
		} catch (Exception e) {
			logger.error("Could not store uploaded file", e);
			BeanUtil.showMessage(FacesMessage.SEVERITY_ERROR, "Error", "Could not store uploaded file " + e.getMessage() );
			return;
		}

		logger.debug("Upload finished");
    }
 
Example 12
@Override
protected void writeErrorSummaryMainText(FacesContext context, ResponseWriter w, FormLayout c, FacesMessage.Severity sev) throws IOException {
    w.startElement("h1", c); // $NON-NLS-1$
    String style = (String)getProperty(PROP_ERRORSUMMARYSTYLE);
    if(StringUtil.isNotEmpty(style)) {
        w.writeAttribute("style", style, null); // $NON-NLS-1$
    }
    String cls = (String)getProperty(PROP_ERRORSUMMARYCLASS);
    if(StringUtil.isNotEmpty(cls)) {
        w.writeAttribute("class", cls, null); // $NON-NLS-1$
    }
    String mainText = c.getErrorSummaryText();
    if(StringUtil.isEmpty(mainText)) {
        mainText = (String)getProperty(PROP_ERRORSUMMARYMAINTEXT);
    }
    writeErrorMessage(context, w, c, mainText);
    w.endElement("h1"); // $NON-NLS-1$
}
 
Example 13
Source Project: sailfish-core   Source File: TestScriptsBean.java    License: Apache License 2.0 6 votes vote down vote up
public void goEditPlainMatrix() {

		long id = Long.parseLong(BeanUtil.getRequestParam("id"));
		logger.info("goEditPlainMatrix invoked {} id[{}]", BeanUtil.getUser(), id);

		MatrixAdapter matrixAdapter = getMatrixAdapterById(id);

		if (matrixAdapter == null) {
			BeanUtil.showMessage(FacesMessage.SEVERITY_ERROR, "Matrix not found", "");
			return;
		}
		try {
			onChange(matrixAdapter);
			setMatrixToEdit(matrixAdapter);
			FacesContext.getCurrentInstance().getExternalContext().redirect(PLAIN_EDITOR);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			BeanUtil.showMessage(FacesMessage.SEVERITY_ERROR, "Error", e.getMessage());
		}
	}
 
Example 14
Source Project: sailfish-core   Source File: TestScriptsBean.java    License: Apache License 2.0 6 votes vote down vote up
public void goEditMatrix() {

		long id = Long.parseLong(BeanUtil.getRequestParam("id"));
		logger.info("goEditMatrix invoked {} id[{}]", BeanUtil.getUser(), id);

		MatrixAdapter matrixAdapter = getMatrixAdapterById(id);

		if (matrixAdapter == null) {
			BeanUtil.showMessage(FacesMessage.SEVERITY_ERROR, "Matrix not found", "");
			return;
		}
		try {
			onChange(matrixAdapter);
			setMatrixToEdit(matrixAdapter);
			FacesContext.getCurrentInstance().getExternalContext().redirect(EXCEL_EDITOR);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			BeanUtil.showMessage(FacesMessage.SEVERITY_ERROR, "Error", e.getMessage());
		}

	}
 
Example 15
/**
 * Remove the messages that are not associated with any particular component
 * from the faces context and store them to the user's session.
 *
 * @return the number of removed messages.
 */
private int saveMessages(FacesContext facesContext) {
	// remove messages from the context
	List<FacesMessage> messages = new ArrayList<FacesMessage>();
	for(Iterator<FacesMessage> i = facesContext.getMessages(null); i.hasNext(); ) {
		messages.add(i.next());
		i.remove();
	}
	// store them in the session
	if(messages.size() == 0) {
		return 0;
	}
	Map<String, Object> sessionMap = facesContext.getExternalContext().getSessionMap();
	// if there already are messages
	@SuppressWarnings("unchecked")
	List<FacesMessage> existingMessages = (List<FacesMessage>) sessionMap.get(sessionToken);
	if(existingMessages != null) {
		existingMessages.addAll(messages);
	}
	else {
		sessionMap.put(sessionToken, messages); // if these are the first messages
	}

	return messages.size();
}
 
Example 16
Source Project: sakai   Source File: SuTool.java    License: Educational Community License v2.0 6 votes vote down vote up
/**
 * Specialized Getters
 */
public boolean getAllowed()
{
	Session sakaiSession = M_session.getCurrentSession();
	FacesContext fc = FacesContext.getCurrentInstance();
	//allow the user to access the tool if they are either a DA user or Super Admin
	if (!M_security.isSuperUser() && sakaiSession.getAttribute("delegatedaccess.accessmapflag") != null)
	{
		message = msgs.getString("unauthorized") + " " + sakaiSession.getUserId();
		log.error("[SuTool] Fatal Error: " + message);
		fc.addMessage("allowed", new FacesMessage(FacesMessage.SEVERITY_FATAL, message, message));
		allowed = false;
	}
	else
	{
		allowed = true;
	}

	return allowed;
}
 
Example 17
Source Project: javaee8-cookbook   Source File: UserView.java    License: Apache License 2.0 6 votes vote down vote up
public void loadUsers() {
    Client client = ClientBuilder.newClient();
    WebTarget target = client.target(URI.create("http://localhost:8080/ch03-rscdi/"));
    User response = target.path("webresources/userservice/getUserFromBean")
            .request()
            .accept(MediaType.APPLICATION_JSON)
            .get(User.class);

    FacesContext.getCurrentInstance()
            .addMessage(null,
                    new FacesMessage("userFromBean: " + response));

    response = target.path("webresources/userservice/getUserFromLocal")
            .request()
            .accept(MediaType.APPLICATION_JSON)
            .get(User.class);

    FacesContext.getCurrentInstance()
            .addMessage(null,
                    new FacesMessage("userFromLocal: " + response));
    client.close();
}
 
Example 18
public void save() {
	log.debug("save check: " + check.getType());
	if ((check.getCondition() != null && !check.getCondition().isEmpty()) || check.isCheckBrokenLinks()) {
		check.setHttpMethod(HttpMethod.GET);
	} else {
		check.setHttpMethod(HttpMethod.HEAD);
	}
	if (pageSelectionController.getSelectedPage() > -1) {
		check.setPage(pageService.findOne(pageSelectionController.getSelectedPage()));
	} else {
		check.setPage(null);
	}
	checkService.save(check);
	if (removeCredentialsAfterSave) {
		checkService.removeCredentials(check.getCredentials().getId());
	}
	clearCheck();
	checkResultsController.loadChecks();
	updateResults();
	pageController.loadPages();
	FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Check saved"));
}
 
Example 19
Source Project: ee8-sandbox   Source File: MessageHandler.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Remove the messages that are not associated with any particular component
 * from the faces context and store them to the user's session.
 *
 * @return the number of removed messages.
 */
private int saveMessages(FacesContext facesContext) {
	// remove messages from the context
	List<FacesMessage> messages = new ArrayList<FacesMessage>();
	for(Iterator<FacesMessage> i = facesContext.getMessages(null); i.hasNext(); ) {
		messages.add(i.next());
		i.remove();
	}
	// store them in the session
	if(messages.size() == 0) {
		return 0;
	}
	Map<String, Object> sessionMap = facesContext.getExternalContext().getSessionMap();
	// if there already are messages
	@SuppressWarnings("unchecked")
	List<FacesMessage> existingMessages = (List<FacesMessage>) sessionMap.get(sessionToken);
	if(existingMessages != null) {
		existingMessages.addAll(messages);
	}
	else {
		sessionMap.put(sessionToken, messages); // if these are the first messages
	}

	return messages.size();
}
 
Example 20
Source Project: oxTrust   Source File: UpdateAttributeAction.java    License: MIT License 6 votes vote down vote up
public String deleteAndAcceptUpdate() {
	if (update && showAttributeDeleteConfirmation) {
		showAttributeDeleteConfirmation = false;
		if (trustService.removeAttribute(this.attribute)) {
			oxTrustAuditService.audit(
					"ATTRIBUTE " + this.attribute.getInum() + " **" + this.attribute.getDisplayName()
							+ "** REMOVED",
					identity.getUser(),
					(HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest());
			facesMessages.add(FacesMessage.SEVERITY_INFO,
					"Attribute '#{updateAttributeAction.attribute.displayName}' removed successfully");
			conversationService.endConversation();
			return OxTrustConstants.RESULT_SUCCESS;
		} else {
			log.error("Failed to remove attribute {}", this.attribute.getInum());
		}
	}
	showAttributeDeleteConfirmation = false;
	facesMessages.add(FacesMessage.SEVERITY_ERROR,
			"Failed to remove attribute '#{updateAttributeAction.attribute.displayName}'");

	return OxTrustConstants.RESULT_FAILURE;
}
 
Example 21
Source Project: sakai   Source File: CSV.java    License: Educational Community License v2.0 6 votes vote down vote up
/**
 * we need to truncate any data greater than MAX_COL_LENGTH chars for the db
 * @param buffer
 * @return
 */
private static StringBuilder truncateIt(StringBuilder buffer)
{
	if (buffer.length() > MAX_COL_LENGTH)   // truncate text longer than MAX_COL_LENGTH
	{
		String truncatedString = buffer.substring(0, MAX_COL_LENGTH);
		buffer = new StringBuilder();
		buffer.append(truncatedString);
		
		if (!truncatingWarningDisplayed) {
			truncatingWarningDisplayed = true;
			FacesContext.getCurrentInstance().addMessage(
					null,
					MessageUtils.getMessage(FacesMessage.SEVERITY_INFO,
							"data_truncated_warning", (new Object[] { new Integer(MAX_COL_LENGTH) }), FacesContext
									.getCurrentInstance()));
		}
	}
	
	return buffer;
}
 
Example 22
Source Project: pragmatic-microservices-lab   Source File: Track.java    License: MIT License 6 votes vote down vote up
public void onTrackById() {

        markersModel = new DefaultMapModel();

        Cargo cargo = cargoRepository.find(new TrackingId(trackingId));

        if (cargo != null) {
            List<HandlingEvent> handlingEvents = handlingEventRepository
                    .lookupHandlingHistoryOfCargo(new TrackingId(trackingId))
                    .getDistinctEventsByCompletionTime();
            this.cargo = new CargoTrackingViewAdapter(cargo, handlingEvents);
            this.destinationCoordinates = net.java.cargotracker.application.util.LocationUtil.getPortCoordinates(cargo.getRouteSpecification().getDestination().getUnLocode().getIdString());

        } else {
            // TODO See if this can be injected.
            FacesContext context = FacesContext.getCurrentInstance();
            FacesMessage message = new FacesMessage(
                    "Cargo with tracking ID: " + trackingId + " not found.");
            message.setSeverity(FacesMessage.SEVERITY_ERROR);
            context.addMessage(null, message);
            this.cargo = null;
        }
    }
 
Example 23
Source Project: CargoTracker-J12015   Source File: Track.java    License: MIT License 6 votes vote down vote up
public void onTrackById() {

        markersModel = new DefaultMapModel();

        Cargo cargo = cargoRepository.find(new TrackingId(trackingId));

        if (cargo != null) {
            List<HandlingEvent> handlingEvents = handlingEventRepository
                    .lookupHandlingHistoryOfCargo(new TrackingId(trackingId))
                    .getDistinctEventsByCompletionTime();
            this.cargo = new CargoTrackingViewAdapter(cargo, handlingEvents);
            this.destinationCoordinates = net.java.cargotracker.application.util.LocationUtil.getPortCoordinates(cargo.getRouteSpecification().getDestination().getUnLocode().getIdString());

        } else {
            // TODO See if this can be injected.
            FacesContext context = FacesContext.getCurrentInstance();
            FacesMessage message = new FacesMessage(
                    "Cargo with tracking ID: " + trackingId + " not found.");
            message.setSeverity(FacesMessage.SEVERITY_ERROR);
            context.addMessage(null, message);
            this.cargo = null;
        }
    }
 
Example 24
/**
 * Remove the messages that are not associated with any particular component
 * from the user's session and add them to the faces context.
 *
 * @return the number of removed messages.
 */
private int restoreMessages(FacesContext facesContext) {
	// remove messages from the session
	Map<String, Object> sessionMap = facesContext.getExternalContext().getSessionMap();
	@SuppressWarnings("unchecked")
	List<FacesMessage> messages = (List<FacesMessage>)sessionMap.remove(sessionToken);
	// store them in the context
	if(messages == null) {
		return 0;
	}
	int restoredCount = messages.size();
	for(Iterator<FacesMessage> i = messages.iterator(); i.hasNext(); ) {
		facesContext.addMessage(null, i.next());
	}

	return restoredCount;
}
 
Example 25
@Override
protected void writeFormRow(FacesContext context, ResponseWriter w, FormLayout c, ComputedFormData formData, UIFormLayoutRow row) throws IOException {
    ComputedRowData rowData = createRowData(context, c, formData, row);

    UIInput edit = row.getForComponent();
    if(edit!=null) {
        // Write the error messages, if any
        if(!formData.isDisableRowError()) {
            Iterator<FacesMessage> msg = ((DominoFacesContext)context).getMessages(edit.getClientId(context));
            if(msg.hasNext()) {
                while(msg.hasNext()) {
                    FacesMessage m = msg.next();
                    writeFormRowError(context, w, c, row, edit, m, rowData);
                }
            }
        }
    }
    
    // The write the children
    writeFormRowData(context, w, c, formData, row, edit, rowData);
}
 
Example 26
Source Project: ipst   Source File: SimulatorInstController.java    License: Mozilla Public License 2.0 6 votes vote down vote up
public String edit(SimulatorInst simulatorInstToEdit) {
    log.log(Level.INFO, " edit enter:: [" + simulatorInstToEdit.toString() + "]");
    FacesContext context = FacesContext.getCurrentInstance();
    ResourceBundle bundle = context.getApplication().getResourceBundle(context, "msg");

    this.simulatorInst = pmanager.findSimulator(simulatorInstToEdit.getSimulator(), simulatorInstToEdit.getVersion());
    try {
        if (simulatorInst != null) {
            log.log(Level.INFO, "Edit SimulatorInst : [" + simulatorInst.getId() + " " + simulatorInst.getSimulator().name() + " " + simulatorInst.getVersion() + "]");
            return "edit";
        } else {
            throw new Exception("Edit: SimulatorInst not found!");
        }
    } catch (Exception e) {
        log.log(Level.WARNING, "edit simulator:: catch an Exception" + e.getMessage());
        String errorMessage = getRootErrorMessage(e);
        FacesMessage m = new FacesMessage(FacesMessage.SEVERITY_ERROR, errorMessage, bundle.getString("edit.failure.msg"));
        facesContext.addMessage(null, m);
        return "edit";
    }
}
 
Example 27
Source Project: sailfish-core   Source File: DictionaryEditorModel.java    License: Apache License 2.0 6 votes vote down vote up
public void saveDictionary() {

        if (dict == null) {
            BeanUtil.addErrorMessage("ERROR", "Can not write dictionary to file.");
            return;
        }

        Map<String, String> defaultValuesCleaned = preSaveCleanNotOverridingDefaultValues();

        try {

            XmlDictionaryStructureWriter.write(dict, context.getWorkspaceDispatcher().createFile(
                    FolderType.ROOT, true, selectedFileContainer.getFileName()));

            BeanUtil.showMessage(FacesMessage.SEVERITY_INFO, "Info", "Dictionary has been saved");
            context.getDictionaryManager().invalidateDictionaries(selectedFileContainer.getURI());

            RequestContext.getCurrentInstance().update("mainDictForm:dropCacheOverlayPanel");

        } catch (Exception ex) {
            logger.error("Can not write dictionary to file.", ex);
            BeanUtil.showMessage(FacesMessage.SEVERITY_ERROR, "Error", "Can not write dictionary to file. " + ex.getMessage());
        } finally {
            afterSaveReturnCleanedDefaultValues(defaultValuesCleaned);
        }
    }
 
Example 28
Source Project: oxTrust   Source File: UpdateRadiusClientAction.java    License: MIT License 6 votes vote down vote up
public String save() {

        try {
            RadiusClient tmpclient = gluuRadiusClientService.getRadiusClientByInum(inum);
            if(client == null) {
                log.debug("Radius client " + inum + " not found.");
                return OxTrustConstants.RESULT_FAILURE;
            }
            if(client.getSecret()!=null && !client.getSecret().isEmpty()) {
                String encsecret = encryptionService.encrypt(client.getSecret());
                client.setSecret(encsecret);
            }else {
                client.setSecret(tmpclient.getSecret());
            }
            client.setDn(tmpclient.getDn());
            client.setInum(tmpclient.getInum());
            gluuRadiusClientService.updateRadiusClient(client);
            facesMessages.add(FacesMessage.SEVERITY_INFO,"#{msg['radius.client.update.success']}");
        }catch(Exception e) {
            log.debug("Could not update client " + inum,e);
            facesMessages.add(FacesMessage.SEVERITY_ERROR,"#{msg['radius.client.update.error']}");
            return OxTrustConstants.RESULT_FAILURE;
        }
        return OxTrustConstants.RESULT_SUCCESS;
    }
 
Example 29
Source Project: sailfish-core   Source File: ConfigBean.java    License: Apache License 2.0 6 votes vote down vote up
public void onApplyEnvParams() {
    logger.info("onApplyEnvParams: start");
    try {

    	EnvironmentSettings environmentSettings = BeanUtil.getSfContext().getEnvironmentManager().getEnvironmentSettings();
    	BeanMap environmentBeanMap = new BeanMap(environmentSettings);

        for (EnvironmentEntity entry : environmentParamsList) {
        	Class<?> type = environmentBeanMap.getType(entry.getParamName());
        	Object convertedValue = BeanUtilsBean.getInstance().getConvertUtils().convert(entry.getParamValue(), type);
            environmentBeanMap.put(entry.getParamName(), convertedValue);
        }
        BeanUtil.getSfContext().getEnvironmentManager().updateEnvironmentSettings((EnvironmentSettings) environmentBeanMap.getBean());
        BeanUtil.showMessage(FacesMessage.SEVERITY_INFO, "INFO", "Successfully saved. Some options will be applied only after Sailfish restart");
    } catch (Exception e){
        logger.error(e.getMessage(), e);
        BeanUtil.showMessage(FacesMessage.SEVERITY_ERROR, "ERROR", e.getMessage());
    }
    logger.info("onApplyEnvParams: end");
}
 
Example 30
Source Project: development   Source File: ConfirmationBeanTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void initialize_SSOAutoLogin_Exception() throws Exception {
    // given
    voUser.setStatus(UserAccountStatus.LOCKED_NOT_CONFIRMED);
    String encodedString = ParameterEncoder.encodeParameters(new String[] {
            userId, orgId, "MPID", String.valueOf(serviceKey) });
    confirmationBean.setEncodedParam(encodedString);
    doReturn(Boolean.TRUE).when(confirmationBean).isServiceProvider();
    doThrow(new LoginException("")).when(confirmationBean).loginUser(
            eq(voUser), anyString(), eq(request), eq(session));

    // when
    confirmationBean.initialize();

    // then
    assertEquals(serviceKey, sessionBean.getSubscribeToServiceKey());
    verify(confirmationBean, times(1)).addMessage(anyString(),
            eq(FacesMessage.SEVERITY_ERROR),
            eq(BaseBean.ERROR_USER_CONFIRMED_LOGIN_FAIL));
}