Java Examples for javax.faces.FacesException
The following java examples will help you to understand the usage of javax.faces.FacesException. These source code samples are taken from different open source projects.
Example 1
Project: BootsFaces-OSP-master File: Tooltip.java View source code |
private static String getAndCheckDelayAttribute(String attributeName, Map<String, Object> attrs, String htmlAttributeName) throws FacesException { Object value = attrs.get(attributeName); if (null != value) { if ((value instanceof String) && ((String) value).length() > 0) { try { Integer.parseInt((String) value); return htmlAttributeName + ":" + value; } catch (NumberFormatException ex) { } } else if (value instanceof Integer) { return htmlAttributeName + ":" + value; } //if we reach this point, the value wasn't accepted as Integer throw new FacesException("The attribute " + attributeName + " has to be numeric. The value '" + value + "' is invalid."); } return null; }
Example 2
Project: sandboxes-master File: ViewExpiredExceptionExceptionHandler.java View source code |
@Override
public void handle() throws FacesException {
for (Iterator<ExceptionQueuedEvent> i = getUnhandledExceptionQueuedEvents().iterator(); i.hasNext(); ) {
ExceptionQueuedEvent event = i.next();
ExceptionQueuedEventContext context = (ExceptionQueuedEventContext) event.getSource();
Throwable exception = context.getException();
if (exception instanceof ViewExpiredException) {
ViewExpiredException viewExpiredException = (ViewExpiredException) exception;
FacesContext facesContext = FacesContext.getCurrentInstance();
Map<String, Object> requestMap = facesContext.getExternalContext().getRequestMap();
NavigationHandler navigationHandler = facesContext.getApplication().getNavigationHandler();
try {
// Push some useful stuff to the request scope for
// use in the page
//requestMap.put("currentViewId", viewExpiredException.getViewId());
navigationHandler.handleNavigation(facesContext, null, "/restore/toslow");
facesContext.renderResponse();
} finally {
i.remove();
}
}
}
// At this point, the queue will not contain any ViewExpiredEvents.
// Therefore, let the parent handle them.
getWrapped().handle();
}
Example 3
Project: jboss-seam-2.3.0.Final-Hibernate.3-master File: EqualityValidator.java View source code |
public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
if (getFor() == null) {
throw new FacesException("Must specify a component to validate equality against");
}
UIComponent otherComponent = findOtherComponent(component);
Object other = new OtherComponent(context, otherComponent).getValue();
if (value == null && other == null) {
// Thats fine
} else if (value != null) {
switch(operator) {
case EQUAL:
if (!value.equals(other)) {
throwValidationException(value, otherComponent, other);
}
break;
case NOT_EQUAL:
if (value.equals(other)) {
throwValidationException(value, otherComponent, other);
}
break;
case GREATER:
if (!(compare(value, other) > 0)) {
throwValidationException(value, otherComponent, other);
}
break;
case GREATER_OR_EQUAL:
if (!(compare(value, other) >= 0)) {
throwValidationException(value, otherComponent, other);
}
break;
case LESS:
if (!(compare(value, other) < 0)) {
throwValidationException(value, otherComponent, other);
}
break;
case LESS_OR_EQUAL:
if (!(compare(value, other) <= 0)) {
throwValidationException(value, otherComponent, other);
}
break;
}
}
}
Example 4
Project: seam-2.2-master File: EqualityValidator.java View source code |
public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
if (getFor() == null) {
throw new FacesException("Must specify a component to validate equality against");
}
UIComponent otherComponent = findOtherComponent(component);
Object other = new OtherComponent(context, otherComponent).getValue();
if (value == null && other == null) {
// Thats fine
} else if (value != null) {
switch(operator) {
case EQUAL:
if (!value.equals(other)) {
throwValidationException(value, otherComponent, other);
}
break;
case NOT_EQUAL:
if (value.equals(other)) {
throwValidationException(value, otherComponent, other);
}
break;
case GREATER:
if (!(compare(value, other) > 0)) {
throwValidationException(value, otherComponent, other);
}
break;
case GREATER_OR_EQUAL:
if (!(compare(value, other) >= 0)) {
throwValidationException(value, otherComponent, other);
}
break;
case LESS:
if (!(compare(value, other) < 0)) {
throwValidationException(value, otherComponent, other);
}
break;
case LESS_OR_EQUAL:
if (!(compare(value, other) <= 0)) {
throwValidationException(value, otherComponent, other);
}
break;
}
}
}
Example 5
Project: seam-revisited-master File: SelectItemsTag.java View source code |
/* (non-Javadoc) * @see org.ajax4jsf.components.taglib.html.HtmlCommandButtonTagBase#setProperties(javax.faces.component.UIComponent) */ protected void setProperties(UIComponent component) { // TODO Auto-generated method stub super.setProperties(component); HtmlSelectItems comp = (HtmlSelectItems) component; if (this._disabled != null) { if (this._disabled.isLiteralText()) { try { java.lang.Boolean __disabled = (java.lang.Boolean) getFacesContext().getApplication().getExpressionFactory().coerceToType(this._disabled.getExpressionString(), java.lang.Boolean.class); comp.setDisabled(__disabled); } catch (ELException e) { throw new FacesException(e); } } else { component.setValueExpression("disabled", this._disabled); } } if (this._escape != null) { if (this._escape.isLiteralText()) { try { java.lang.Boolean __escape = (java.lang.Boolean) getFacesContext().getApplication().getExpressionFactory().coerceToType(this._escape.getExpressionString(), java.lang.Boolean.class); comp.setEscape(__escape); } catch (ELException e) { throw new FacesException(e); } } else { component.setValueExpression("escape", this._escape); } } if (this._hideNoSelectionLabel != null) { if (this._hideNoSelectionLabel.isLiteralText()) { try { java.lang.Boolean __hideNoSelectionLabel = (java.lang.Boolean) getFacesContext().getApplication().getExpressionFactory().coerceToType(this._hideNoSelectionLabel.getExpressionString(), java.lang.Boolean.class); comp.setHideNoSelectionLabel(__hideNoSelectionLabel); } catch (ELException e) { throw new FacesException(e); } } else { component.setValueExpression("hideNoSelectionLabel", this._hideNoSelectionLabel); } } if (this._itemValue != null) { if (this._itemValue.isLiteralText()) { try { java.lang.Object __itemValue = (java.lang.Object) getFacesContext().getApplication().getExpressionFactory().coerceToType(this._itemValue.getExpressionString(), java.lang.Object.class); comp.setItemValue(__itemValue); } catch (ELException e) { throw new FacesException(e); } } else { component.setValueExpression("itemValue", this._itemValue); } } if (this._label != null) { if (this._label.isLiteralText()) { try { java.lang.String __label = (java.lang.String) getFacesContext().getApplication().getExpressionFactory().coerceToType(this._label.getExpressionString(), java.lang.String.class); comp.setLabel(__label); } catch (ELException e) { throw new FacesException(e); } } else { component.setValueExpression("label", this._label); } } if (this._noSelectionLabel != null) { if (this._noSelectionLabel.isLiteralText()) { try { java.lang.String __noSelectionLabel = (java.lang.String) getFacesContext().getApplication().getExpressionFactory().coerceToType(this._noSelectionLabel.getExpressionString(), java.lang.String.class); comp.setNoSelectionLabel(__noSelectionLabel); } catch (ELException e) { throw new FacesException(e); } } else { component.setValueExpression("noSelectionLabel", this._noSelectionLabel); } } if (this._value != null) { if (this._value.isLiteralText()) { try { java.lang.Object __value = (java.lang.Object) getFacesContext().getApplication().getExpressionFactory().coerceToType(this._value.getExpressionString(), java.lang.Object.class); comp.setValue(__value); } catch (ELException e) { throw new FacesException(e); } } else { component.setValueExpression("value", this._value); } } if (this._var != null) { comp.setVar(this._var); } }
Example 6
Project: seam2jsf2-master File: SelectItemsTag.java View source code |
/* (non-Javadoc) * @see org.ajax4jsf.components.taglib.html.HtmlCommandButtonTagBase#setProperties(javax.faces.component.UIComponent) */ protected void setProperties(UIComponent component) { // TODO Auto-generated method stub super.setProperties(component); HtmlSelectItems comp = (HtmlSelectItems) component; if (this._disabled != null) { if (this._disabled.isLiteralText()) { try { java.lang.Boolean __disabled = (java.lang.Boolean) getFacesContext().getApplication().getExpressionFactory().coerceToType(this._disabled.getExpressionString(), java.lang.Boolean.class); comp.setDisabled(__disabled); } catch (ELException e) { throw new FacesException(e); } } else { component.setValueExpression("disabled", this._disabled); } } if (this._escape != null) { if (this._escape.isLiteralText()) { try { java.lang.Boolean __escape = (java.lang.Boolean) getFacesContext().getApplication().getExpressionFactory().coerceToType(this._escape.getExpressionString(), java.lang.Boolean.class); comp.setEscape(__escape); } catch (ELException e) { throw new FacesException(e); } } else { component.setValueExpression("escape", this._escape); } } if (this._hideNoSelectionLabel != null) { if (this._hideNoSelectionLabel.isLiteralText()) { try { java.lang.Boolean __hideNoSelectionLabel = (java.lang.Boolean) getFacesContext().getApplication().getExpressionFactory().coerceToType(this._hideNoSelectionLabel.getExpressionString(), java.lang.Boolean.class); comp.setHideNoSelectionLabel(__hideNoSelectionLabel); } catch (ELException e) { throw new FacesException(e); } } else { component.setValueExpression("hideNoSelectionLabel", this._hideNoSelectionLabel); } } if (this._itemValue != null) { if (this._itemValue.isLiteralText()) { try { java.lang.Object __itemValue = (java.lang.Object) getFacesContext().getApplication().getExpressionFactory().coerceToType(this._itemValue.getExpressionString(), java.lang.Object.class); comp.setItemValue(__itemValue); } catch (ELException e) { throw new FacesException(e); } } else { component.setValueExpression("itemValue", this._itemValue); } } if (this._label != null) { if (this._label.isLiteralText()) { try { java.lang.String __label = (java.lang.String) getFacesContext().getApplication().getExpressionFactory().coerceToType(this._label.getExpressionString(), java.lang.String.class); comp.setLabel(__label); } catch (ELException e) { throw new FacesException(e); } } else { component.setValueExpression("label", this._label); } } if (this._noSelectionLabel != null) { if (this._noSelectionLabel.isLiteralText()) { try { java.lang.String __noSelectionLabel = (java.lang.String) getFacesContext().getApplication().getExpressionFactory().coerceToType(this._noSelectionLabel.getExpressionString(), java.lang.String.class); comp.setNoSelectionLabel(__noSelectionLabel); } catch (ELException e) { throw new FacesException(e); } } else { component.setValueExpression("noSelectionLabel", this._noSelectionLabel); } } if (this._value != null) { if (this._value.isLiteralText()) { try { java.lang.Object __value = (java.lang.Object) getFacesContext().getApplication().getExpressionFactory().coerceToType(this._value.getExpressionString(), java.lang.Object.class); comp.setValue(__value); } catch (ELException e) { throw new FacesException(e); } } else { component.setValueExpression("value", this._value); } } if (this._var != null) { comp.setVar(this._var); } }
Example 7
Project: taylor-seam-jsf2-master File: EqualityValidator.java View source code |
public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
if (getFor() == null) {
throw new FacesException("Must specify a component to validate equality against");
}
UIComponent otherComponent = findOtherComponent(component);
Object other = new OtherComponent(context, otherComponent).getValue();
if (value == null && other == null) {
// Thats fine
} else if (value != null) {
switch(operator) {
case EQUAL:
if (!value.equals(other)) {
throwValidationException(value, otherComponent, other);
}
break;
case NOT_EQUAL:
if (value.equals(other)) {
throwValidationException(value, otherComponent, other);
}
break;
case GREATER:
if (!(compare(value, other) > 0)) {
throwValidationException(value, otherComponent, other);
}
break;
case GREATER_OR_EQUAL:
if (!(compare(value, other) >= 0)) {
throwValidationException(value, otherComponent, other);
}
break;
case LESS:
if (!(compare(value, other) < 0)) {
throwValidationException(value, otherComponent, other);
}
break;
case LESS_OR_EQUAL:
if (!(compare(value, other) <= 0)) {
throwValidationException(value, otherComponent, other);
}
break;
}
}
}
Example 8
Project: alvsanand-master File: ExceptionFilter.java View source code |
private Throwable searchLastFacesExceptionOrELException(Throwable throwable) {
if (throwable == null) {
return null;
}
if (throwable instanceof javax.faces.FacesException || throwable instanceof javax.el.ELException) {
if (throwable.getCause() != null) {
Throwable nextFacesException = searchLastFacesExceptionOrELException(throwable.getCause());
if (nextFacesException != null) {
return nextFacesException;
} else {
return throwable;
}
} else {
return throwable;
}
} else {
return searchLastFacesExceptionOrELException(throwable.getCause());
}
}
Example 9
Project: coala-master File: JSFExceptionHandler.java View source code |
@Override public void handle() throws FacesException { Iterator<ExceptionQueuedEvent> itr = getUnhandledExceptionQueuedEvents().iterator(); while (itr.hasNext()) { ExceptionQueuedEvent event = itr.next(); ExceptionQueuedEventContext context = (ExceptionQueuedEventContext) event.getSource(); Throwable thr = context.getException(); if (thr instanceof FacesException) { FacesContext fc = FacesContext.getCurrentInstance(); NavigationHandler nav = fc.getApplication().getNavigationHandler(); try { fc.addMessage(null, new FacesMessage("Server not available")); nav.handleNavigation(fc, null, "/login.xhtml"); fc.renderResponse(); } finally { itr.remove(); } } } getWrapped().handle(); }
Example 10
Project: com.idega.builder-master File: PropertyTagHandler.java View source code |
public void apply(FaceletContext ctx, UIComponent parent) throws IOException, FacesException, FaceletException, ELException {
this.parent = parent;
TagAttribute nameAttr = this.getAttribute("name");
if (nameAttr != null) {
this.name = nameAttr.getValue();
}
TagAttribute valueAttr = this.getAttribute("value");
if (valueAttr != null) {
this.value = valueAttr.getValue();
}
if (this.nameChild != null) {
this.name = nameChild.getName();
}
if (this.valueChildrenHandlers != null) {
if (!this.valueChildrenHandlers.isEmpty()) {
ArrayList valuesList = new ArrayList();
for (Iterator iterator = valueChildrenHandlers.iterator(); iterator.hasNext(); ) {
PropertyValueTagHandler handler = (PropertyValueTagHandler) iterator.next();
valuesList.add(handler.getValue());
}
this.values = (String[]) valuesList.toArray(new String[0]);
}
}
setProperties();
}
Example 11
Project: curso-javaee-primefaces-master File: JsfExceptionHandler.java View source code |
@Override
public void handle() throws FacesException {
Iterator<ExceptionQueuedEvent> events = getUnhandledExceptionQueuedEvents().iterator();
while (events.hasNext()) {
ExceptionQueuedEvent event = events.next();
ExceptionQueuedEventContext context = (ExceptionQueuedEventContext) event.getSource();
Throwable exception = context.getException();
NegocioException negocioException = getNegocioException(exception);
boolean handled = false;
try {
if (exception instanceof ViewExpiredException) {
handled = true;
redirect("/");
} else if (negocioException != null) {
handled = true;
FacesUtil.addErrorMessage(negocioException.getMessage());
} else {
handled = true;
log.error("Erro de sistema: " + exception.getMessage(), exception);
redirect("/Erro.xhtml");
}
} finally {
if (handled) {
events.remove();
}
}
}
getWrapped().handle();
}
Example 12
Project: dev-examples-master File: ActionMapperTagHandler.java View source code |
public void apply(FaceletContext ctx, UIComponent parent) throws IOException, FacesException, FaceletException, ELException {
MethodExpression actionExpression = remap(ctx, ACTION, String.class, ACTION_PARAM_TYPES);
MethodExpression actionListenerExpression = remap(ctx, ACTION_LISTENER, null, ACTION_LISTENER_PARAM_TYPES);
VariableMapper initialVarMapper = ctx.getVariableMapper();
try {
if (actionExpression == null) {
actionExpression = NOOP_ACTION_EXPRESSION;
}
initialVarMapper.setVariable(MAPPED_ACTION, ctx.getExpressionFactory().createValueExpression(actionExpression, MethodExpression.class));
if (actionListenerExpression == null) {
actionListenerExpression = NOOP_ACTION_LISTENER_EXPRESSION;
}
initialVarMapper.setVariable(MAPPED_ACTION_LISTENER, ctx.getExpressionFactory().createValueExpression(actionListenerExpression, MethodExpression.class));
ctx.setVariableMapper(initialVarMapper);
nextHandler.apply(ctx, parent);
} finally {
ctx.setVariableMapper(initialVarMapper);
}
}
Example 13
Project: faces-ext-master File: InterceptingLifecycle.java View source code |
@Override public void execute(FacesContext context) throws FacesException { try { System.out.println("execute(...)"); getWrapped().execute(context); } catch (FacesException intercepted) { System.out.println("===>>> Intercepted Throwable from execute()"); intercepted.printStackTrace(); FacesContext.getCurrentInstance().renderResponse(); throw intercepted; } }
Example 14
Project: prime-arquillian-master File: WizardRenderer.java View source code |
protected void encodeScript(FacesContext context, Wizard wizard) throws IOException {
ResponseWriter writer = context.getResponseWriter();
String clientId = wizard.getClientId(context);
UIComponent form = ComponentUtils.findParentForm(context, wizard);
if (form == null) {
throw new FacesException("Wizard : \"" + clientId + "\" must be inside a form element");
}
startScript(writer, clientId);
writer.write("$(function() {");
writer.write("PrimeFaces.cw('Wizard','" + wizard.resolveWidgetVar() + "',{");
writer.write("id:'" + clientId + "'");
writer.write(",showStepStatus:" + wizard.isShowStepStatus());
writer.write(",showNavBar:" + wizard.isShowNavBar());
if (wizard.getOnback() != null) {
writer.write(",onback:function(){" + wizard.getOnback() + "}");
}
if (wizard.getOnnext() != null) {
writer.write(",onnext:function(){" + wizard.getOnnext() + "}");
}
//all steps
writer.write(",steps:[");
boolean firstStep = true;
String defaultStep = null;
for (Iterator<UIComponent> children = wizard.getChildren().iterator(); children.hasNext(); ) {
UIComponent child = children.next();
if (child instanceof Tab && child.isRendered()) {
Tab tab = (Tab) child;
if (defaultStep == null) {
defaultStep = tab.getId();
}
if (!firstStep) {
writer.write(",");
} else {
firstStep = false;
}
writer.write("'" + tab.getId() + "'");
}
}
writer.write("]");
//current step
if (wizard.getStep() == null) {
wizard.setStep(defaultStep);
}
writer.write(",initialStep:'" + wizard.getStep() + "'");
writer.write("});});");
endScript(writer);
}
Example 15
Project: richfaces-master File: Pages.java View source code |
/**
*
*/
private List<PageDescriptionBean> getPagesByPattern(Pattern pattern, String path) {
List<PageDescriptionBean> pageList = new ArrayList<PageDescriptionBean>();
Set<String> resourcePaths = getExternalContext().getResourcePaths(path);
for (Iterator<String> iterator = resourcePaths.iterator(); iterator.hasNext(); ) {
String page = resourcePath(iterator.next());
if (pattern.matcher(page).matches() && !page.endsWith("/index.xhtml")) {
InputStream pageInputStream = getExternalContext().getResourceAsStream(page);
String title = page;
if (null != pageInputStream) {
byte[] head = new byte[2048];
try {
int readed = pageInputStream.read(head);
String headString = new String(head, 0, readed);
if (title.endsWith("input/")) {
System.out.println(headString);
}
Matcher titleMatcher = titlePattern.matcher(headString);
if (titleMatcher.find() && titleMatcher.group(1).length() > 0) {
title = titleMatcher.group(1);
}
} catch (IOException e) {
throw new FacesException("can't read directory content", e);
} finally {
try {
pageInputStream.close();
} catch (IOException e) {
}
}
}
pageList.add(new PageDescriptionBean(page, title));
}
}
Collections.sort(pageList);
return pageList;
}
Example 16
Project: richfaces-sandbox-master File: ImageSelectToolRenderer.java View source code |
protected Map<String, Object> getOptions(FacesContext context, AbstractImageSelectTool component) throws IOException {
Map<String, Object> options = new HashMap<String, Object>();
addOptionIfSet("onchange", component.getOnchange(), options);
addOptionIfSet("onselect", component.getOnselect(), options);
Rectangle rect = (Rectangle) component.getValue();
if (rect != null) {
Map<String, Object> selection = new HashMap<String, Object>();
selection.put("x", rect.x);
selection.put("y", rect.y);
selection.put("width", rect.width);
selection.put("height", rect.height);
addOptionIfSet("selection", selection, options);
}
addOptionIfSet("maxWidth", component.getMaxWidth(), options);
addOptionIfSet("maxHeight", component.getMaxHeight(), options);
addOptionIfSet("minWidth", component.getMinWidth(), options);
addOptionIfSet("minHeight", component.getMinHeight(), options);
addOptionIfSet("aspectRatio", component.getAspectRatio(), options);
addOptionIfSet("backgroundColor", component.getBackgroundColor(), options);
addOptionIfSet("backgroundOpacity", component.getBackgroundOpacity(), options);
addOptionIfSet("trueSizeWidth", component.getTrueSizeWidth(), options);
addOptionIfSet("trueSizeHeight", component.getTrueSizeHeight(), options);
String forAttribute = component.getTarget();
UIComponent forComp;
String forClientId;
if (forAttribute == null || forAttribute.length() == 0) {
forComp = component;
while ((forComp = forComp.getParent()) != null) {
if (forComp instanceof javax.faces.component.UIGraphic) {
break;
}
}
/**
* We are not interested in UIViewRoot
*/
if (forComp != null && forComp.getParent() == null) {
forComp = null;
}
} else {
forComp = getUtils().findComponentFor(context, component.getParent(), forAttribute);
}
if (forComp == null) {
throw new FacesException("could not find target for croptool " + component.getId());
}
forClientId = forComp.getClientId(context);
addOptionIfSet("targetId", forClientId, options);
addOptionIfSet("inputId", getInputId(context, component), options);
return options;
}
Example 17
Project: showcase-master File: SyntaxHighlighter.java View source code |
private void renderStream(FacesContext context, InputStream stream) throws IOException {
ResponseWriter writer = context.getResponseWriter();
InputStreamReader in = new InputStreamReader(stream);
char[] temp = new char[1024];
try {
int bytes;
while ((bytes = in.read(temp)) > 0) {
writer.writeText(temp, 0, bytes);
}
} catch (IOException e) {
throw new FacesException(e);
} finally {
in.close();
}
}
Example 18
Project: spring-webflow-master File: FlowResourceResolver.java View source code |
public URL resolveUrl(String path) {
if (!JsfUtils.isFlowRequest()) {
return this.delegateResolver.resolveUrl(path);
}
try {
RequestContext context = RequestContextHolder.getRequestContext();
ApplicationContext flowContext = context.getActiveFlow().getApplicationContext();
if (flowContext == null) {
throw new IllegalStateException("A Flow ApplicationContext is required to resolve Flow View Resources");
}
ApplicationContext appContext = flowContext.getParent();
Resource viewResource = appContext.getResource(path);
if (viewResource.exists()) {
return viewResource.getURL();
} else {
return this.delegateResolver.resolveUrl(path);
}
} catch (IOException ex) {
throw new FacesException(ex);
}
}
Example 19
Project: behave-master File: GridExceptionHandler.java View source code |
@Override
public void handle() throws FacesException {
for (Iterator<ExceptionQueuedEvent> i = getUnhandledExceptionQueuedEvents().iterator(); i.hasNext(); ) {
ExceptionQueuedEvent exceptionQueuedEvent = i.next();
ExceptionQueuedEventContext exceptionQueuedEventContext = (ExceptionQueuedEventContext) exceptionQueuedEvent.getSource();
Throwable throwable = exceptionQueuedEventContext.getException();
if (throwable instanceof Throwable) {
Throwable t = (Throwable) throwable;
if (t.getCause() instanceof TestGridException) {
TestGridException e = (TestGridException) t.getCause();
FacesUtil.addMessage(e.getObjectMessage(), e.getParams());
} else if (t instanceof ViewExpiredException) {
ViewExpiredException vee = (ViewExpiredException) t;
FacesContext fc = FacesContext.getCurrentInstance();
NavigationHandler nav = fc.getApplication().getNavigationHandler();
try {
fc.getExternalContext().getFlash().put("expiredViewId", vee.getViewId());
nav.handleNavigation(fc, null, "/private/pages/index?faces-redirect=true");
fc.renderResponse();
} finally {
i.remove();
}
} else {
String[] param = { throwable.getMessage() };
FacesUtil.addMessage(ErrorMessage.UNEXPECTED, param, throwable);
}
}
}
}
Example 20
Project: blaze-faces-master File: InputFileRenderer.java View source code |
@Override public void decode(FacesContext context, UIComponent component) { InputFile inputFile = (InputFile) component; if (!inputFile.isDisabled()) { String clientId = inputFile.getClientId(context); Part part = null; try { part = ((HttpServletRequest) context.getExternalContext().getRequest()).getPart(clientId); } catch (IOException ex) { throw new FacesException("Could not get the part", ex); } catch (ServletException ex) { throw new FacesException("Could not get the part", ex); } if (part != null) { if (part.getName().equals("")) { inputFile.setSubmittedValue(""); } else { inputFile.setSubmittedValue(part); } } } }
Example 21
Project: cats-master File: CustomExceptionHandler.java View source code |
@Override
public void handle() throws FacesException {
Iterator<ExceptionQueuedEvent> i = getUnhandledExceptionQueuedEvents().iterator();
while (i.hasNext()) {
ExceptionQueuedEvent event = i.next();
ExceptionQueuedEventContext context = (ExceptionQueuedEventContext) event.getSource();
Throwable throwable = context.getException();
final FacesContext fc = FacesContext.getCurrentInstance();
final Map<String, Object> requestMap = fc.getExternalContext().getRequestMap();
final NavigationHandler nav = fc.getApplication().getNavigationHandler();
try {
requestMap.put("exceptionMessage", throwable);
if (throwable instanceof ViewExpiredException) {
if (authController != null) {
authController.logout();
} else {
nav.handleNavigation(fc, null, "/errors/session_expired.xhtml");
}
} else {
nav.handleNavigation(fc, null, "/errors/error.xhtml");
}
fc.renderResponse();
} finally {
i.remove();
}
}
getWrapped().handle();
}
Example 22
Project: cocoon-master File: SelectOneRadioTag.java View source code |
protected void setProperties(UIComponent component) { super.setProperties(component); UISelectOne select; try { select = (UISelectOne) component; } catch (ClassCastException cce) { throw new FacesException("Tag <" + getClass().getName() + "> expected UISelectOne. " + "Got <" + component.getClass().getName() + ">"); } if (converter != null) { if (FacesUtils.isExpression(converter)) { select.setValueBinding("converter", createValueBinding(converter)); } else { select.setConverter(getApplication().createConverter(converter)); } } if (immediate != null) { if (FacesUtils.isExpression(immediate)) { select.setValueBinding("immediate", createValueBinding(immediate)); } else { select.setImmediate(BooleanUtils.toBoolean(immediate)); } } if (required != null) { if (FacesUtils.isExpression(required)) { select.setValueBinding("required", createValueBinding(required)); } else { select.setRequired(BooleanUtils.toBoolean(required)); } } if (validator != null) { if (FacesUtils.isExpression(validator)) { MethodBinding vb = getApplication().createMethodBinding(validator, new Class[] { FacesContext.class, UIComponent.class, Object.class }); select.setValidator(vb); } else { throw new FacesException("Tag <" + getClass().getName() + "> validator must be an expression. " + "Got <" + validator + ">"); } } if (value != null) { if (FacesUtils.isExpression(value)) { select.setValueBinding("value", createValueBinding(value)); } else { select.setValue(value); } } if (valueChangeListener != null) { if (FacesUtils.isExpression(valueChangeListener)) { MethodBinding vb = getApplication().createMethodBinding(valueChangeListener, new Class[] { ValueChangeEvent.class }); select.setValueChangeListener(vb); } else { throw new FacesException("Tag <" + getClass().getName() + "> valueChangeListener must be an expression. " + "Got <" + valueChangeListener + ">"); } } setProperty(component, "accesskey", accesskey); setIntegerProperty(component, "border", border); setProperty(component, "dir", dir); setBooleanProperty(component, "disabled", disabled); setProperty(component, "disabledClass", disabledClass); setProperty(component, "enabledClass", enabledClass); setProperty(component, "lang", lang); setProperty(component, "layout", layout); setProperty(component, "onblur", onblur); setProperty(component, "onchange", onchange); setProperty(component, "onclick", onclick); setProperty(component, "ondblclick", ondblclick); setProperty(component, "onfocus", onfocus); setProperty(component, "onkeydown", onkeydown); setProperty(component, "onkeypress", onkeypress); setProperty(component, "onkeyup", onkeyup); setProperty(component, "onmousedown", onmousedown); setProperty(component, "onmousemove", onmousemove); setProperty(component, "onmouseout", onmouseout); setProperty(component, "onmouseover", onmouseover); setProperty(component, "onmouseup", onmouseup); setProperty(component, "onselect", onselect); setBooleanProperty(component, "readonly", readonly); setProperty(component, "style", style); setProperty(component, "styleClass", styleClass); setProperty(component, "tabindex", tabindex); setProperty(component, "title", title); }
Example 23
Project: core-master File: MyExceptionHandler.java View source code |
@Override
public void handle() throws FacesException {
if (getUnhandledExceptionQueuedEvents().iterator().hasNext()) {
FacesContext facesContext = FacesContext.getCurrentInstance();
NavigationHandler navHandler = facesContext.getApplication().getNavigationHandler();
navHandler.handleNavigation(facesContext, null, "/error.jsf?faces-redirect=true");
}
}
Example 24
Project: deltaspike-solder-master File: CatchExceptionHandler.java View source code |
@Override
public void handle() throws FacesException {
log.trace("Handling Exceptions");
for (Iterator<ExceptionQueuedEvent> it = getUnhandledExceptionQueuedEvents().iterator(); it.hasNext(); ) {
Throwable t = it.next().getContext().getException();
log.trace(MessageFormat.format("Handling Exception {0}", t.getClass().getName()));
ExceptionToCatchEvent catchEvent = new ExceptionToCatchEvent(t, FacesLiteral.INSTANCE);
try {
if (log.isTraceEnabled()) {
log.trace("Firing event");
}
beanManager.fireEvent(catchEvent);
} catch (Exception e) {
if (!e.equals(t)) {
log.debug("Throwing exception thrown from within Seam Catch");
throw new RuntimeException(e);
}
continue;
}
if (catchEvent.isHandled()) {
log.debug(MessageFormat.format("Exception handled {0}", t.getClass().getName()));
it.remove();
}
}
if (getUnhandledExceptionQueuedEvents().iterator().hasNext()) {
log.debug("Exceptions remain, will be thrown outside of JSF");
getWrapped().handle();
}
}
Example 25
Project: faces-master File: CatchExceptionHandler.java View source code |
@Override
public void handle() throws FacesException {
log.trace("Handling Exceptions");
for (Iterator<ExceptionQueuedEvent> it = getUnhandledExceptionQueuedEvents().iterator(); it.hasNext(); ) {
Throwable t = it.next().getContext().getException();
log.trace(MessageFormat.format("Handling Exception {0}", t.getClass().getName()));
ExceptionToCatch catchEvent = new ExceptionToCatch(t, FacesLiteral.INSTANCE);
try {
if (log.isTraceEnabled()) {
log.trace("Firing event");
}
beanManager.fireEvent(catchEvent);
} catch (Exception e) {
if (!e.equals(t)) {
log.debug("Throwing exception thrown from within Seam Catch");
throw new RuntimeException(e);
}
continue;
}
if (catchEvent.isHandled()) {
log.debug(MessageFormat.format("Exception handled {0}", t.getClass().getName()));
it.remove();
}
}
if (getUnhandledExceptionQueuedEvents().iterator().hasNext()) {
log.debug("Exceptions remain, will be thrown outside of JSF");
getWrapped().handle();
}
}
Example 26
Project: hdiv-archive-master File: HtmlOutputLinkExtension.java View source code |
/*
* (non-Javadoc)
*
* @see javax.faces.component.UIComponent#encodeBegin(javax.faces.context.
* FacesContext)
*/
public void encodeBegin(FacesContext context) throws IOException {
if (log.isDebugEnabled()) {
log.debug("encodeBegin");
}
try {
ExternalContext externalContext = context.getExternalContext();
HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();
String url = this.getValue().toString();
// Check if it is necessary to add the state
if (!RequestUtilsHDIV.isInternalUrl(request, url)) {
if (log.isDebugEnabled()) {
log.debug("is external url");
}
super.encodeBegin(context);
return;
}
HDIVConfig hdivConfig = HDIVUtil.getHDIVConfig(request.getSession().getServletContext());
// state
if (!hdivConfig.isValidationInUrlsWithoutParamsActivated() && !url.contains("?") && !hasUIParamChilds()) {
super.encodeBegin(context);
return;
}
// an image
if (RequestUtilsHDIV.isResourceUrl(hdivConfig, url)) {
if (log.isDebugEnabled()) {
log.debug("is resource url");
}
super.encodeBegin(context);
return;
}
String anchor = HDIVRequestUtils.getAnchorFromUrl(url);
url = HDIVRequestUtils.removeAnchorFromUrl(url);
IDataComposer dataComposer = HDIVUtil.getDataComposer(request);
// Confidentiality is disabled, so the url doesn't change
String encodedUrl = RequestUtilsHDIV.composeURL(request, dataComposer, url);
boolean hasUIParams = false;
Iterator it = this.getChildren().iterator();
while (it.hasNext()) {
UIComponent comp = (UIComponent) it.next();
if (comp instanceof UIParameter) {
hasUIParams = true;
break;
}
}
String requestId = dataComposer.endRequest();
String hdivParameter = (String) externalContext.getSessionMap().get(Constants.HDIV_PARAMETER);
if (hasUIParams) {
this.setValue(encodedUrl);
// Add a children UIParam component with Hdiv's state
UIParameter paramComponent = (UIParameter) context.getApplication().createComponent(UIParameter.COMPONENT_TYPE);
paramComponent.setName(hdivParameter);
paramComponent.setValue(requestId);
this.getChildren().add(paramComponent);
} else {
// Add state directly in the outputLink's value
String finalUrl = RequestUtilsHDIV.addHDIVState(hdivParameter, requestId, encodedUrl, anchor);
this.setValue(finalUrl);
}
} catch (FacesException e) {
log.error("Error en HtmlOutputLinkExtension: " + e.getMessage());
throw e;
}
super.encodeBegin(context);
}
Example 27
Project: imixs-marty-master File: ViewExpiredExceptionExceptionHandler.java View source code |
@Override
public void handle() throws FacesException {
for (Iterator<ExceptionQueuedEvent> i = getUnhandledExceptionQueuedEvents().iterator(); i.hasNext(); ) {
ExceptionQueuedEvent event = i.next();
ExceptionQueuedEventContext context = (ExceptionQueuedEventContext) event.getSource();
Throwable t = context.getException();
if (t instanceof ViewExpiredException) {
ViewExpiredException vee = (ViewExpiredException) t;
FacesContext fc = FacesContext.getCurrentInstance();
Map<String, Object> requestMap = fc.getExternalContext().getRequestMap();
NavigationHandler nav = fc.getApplication().getNavigationHandler();
try {
// Push some useful stuff to the request scope for
// use in the page
requestMap.put("currentViewId", vee.getViewId());
nav.handleNavigation(fc, null, "sessionexpired");
fc.renderResponse();
} finally {
i.remove();
}
}
}
// At this point, the queue will not contain any ViewExpiredEvents.
// Therefore, let the parent handle them.
getWrapped().handle();
}
Example 28
Project: jsfunitng-master File: PhaserContextFactoryWrapper.java View source code |
public FacesContext getFacesContext(Object context, Object request, Object response, Lifecycle lifecycle) throws FacesException {
FacesContext facesContext = new WrappedFacesContext(delegate.getFacesContext(context, request, response, lifecycle));
if (request instanceof HttpServletRequest) {
HttpServletRequest httpReq = (HttpServletRequest) request;
@SuppressWarnings("unchecked") Instance<LifecycleManagerStore> store = (Instance<LifecycleManagerStore>) httpReq.getAttribute(WarpCommons.LIFECYCLE_MANAGER_STORE_REQUEST_ATTRIBUTE);
facesContext.getAttributes().put(INITIALIZED, Boolean.FALSE);
if (store != null && store.get() != null) {
try {
store.get().bind(FacesContext.class, facesContext);
facesContext.getAttributes().put(INITIALIZED, Boolean.TRUE);
} catch (ObjectAlreadyAssociatedException e) {
throw new IllegalStateException(e);
}
}
}
return facesContext;
}
Example 29
Project: mojarra-master File: TestMessageFactoryImpl.java View source code |
//
// General Methods
//
public void testGetMethods() {
// boolean gotException = false;
// FacesMessage msg = null;
//
// FacesContext facesContext = getFacesContext();
// assert (facesContext != null);
//
// System.out.println("Testing get methods");
// try {
// msg = MessageFactory.getMessage((FacesContext) null, (String) null);
// } catch (NullPointerException fe) {
// gotException = true;
// }
// assertTrue(gotException);
// gotException = false;
// msg = null;
//
// // if msgId doesn't exist in the resource, null must be returned
// try {
// msg = MessageFactory.getMessage(facesContext, "MSG01", "param1");
// assertTrue(null == msg);
// } catch (FacesException fe) {
// assertTrue(false);
// }
//
//
// Object[] params1 = {"JavaServerFaces"};
// msg = MessageFactory.getMessage(facesContext, "MSG0001", params1);
// assertTrue(msg != null);
// assertTrue(
// (msg.getSummary()).equals(
// "'JavaServerFaces' is not a valid number."));
//
// msg = MessageFactory.getMessage(facesContext, "MSG0003", "userId");
// assertTrue(msg != null);
// assertTrue(
// (msg.getSummary()).equals("'userId' field cannot be empty."));
//
// msg =
// MessageFactory.getMessage(facesContext, "MSG0004", "userId",
// "1000", "10000");
// assertTrue(msg != null);
// assertTrue(
// (msg.getSummary()).equals(
// "'userId' out of range. Value should be between '1000' and '10000'."));
}
Example 30
Project: muikku-master File: ExceptionHandler.java View source code |
@Override public void handle() throws FacesException { for (final Iterator<ExceptionQueuedEvent> queuedEventIterator = getUnhandledExceptionQueuedEvents().iterator(); queuedEventIterator.hasNext(); ) { ExceptionQueuedEvent queuedEvent = queuedEventIterator.next(); ExceptionQueuedEventContext queuedEventContext = queuedEvent.getContext(); Throwable exception = queuedEventContext.getException(); while ((exception instanceof FacesException || exception instanceof EJBException || exception instanceof ELException || exception instanceof RewriteException || exception instanceof CreationException || exception instanceof IllegalStateException) && exception.getCause() != null) { exception = exception.getCause(); } FacesContext facesContext = FacesContext.getCurrentInstance(); ExternalContext externalContext = facesContext.getExternalContext(); try { if (exception instanceof AuthorizationException) { externalContext.setResponseStatus(HttpServletResponse.SC_FORBIDDEN); renderView("/error/access-denied.jsf"); } else if (exception instanceof FileNotFoundException) { externalContext.setResponseStatus(HttpServletResponse.SC_NOT_FOUND); renderView("/error/not-found.jsf"); } else { throw new FacesException(exception); } } finally { queuedEventIterator.remove(); } } getWrapped().handle(); }
Example 31
Project: myfaces-ext-cdi-master File: FlowNavigationHandler.java View source code |
private void processViewDefinitionEntry(FacesContext facesContext, ViewDefinitionEntry entry) {
String targetViewId = entry.getViewId();
if (NavigationMode.REDIRECT.equals(entry.getNavigationMode())) {
ExternalContext externalContext = facesContext.getExternalContext();
ViewHandler viewHandler = facesContext.getApplication().getViewHandler();
String redirectPath = viewHandler.getActionURL(facesContext, targetViewId);
try {
externalContext.redirect(externalContext.encodeActionURL(redirectPath));
} catch (IOException e) {
throw new FacesException(e.getMessage(), e);
}
} else {
ViewHandler viewHandler = facesContext.getApplication().getViewHandler();
UIViewRoot viewRoot = viewHandler.createView(facesContext, targetViewId);
facesContext.setViewRoot(viewRoot);
facesContext.renderResponse();
}
}
Example 32
Project: myfaces-master File: VariableResolverImpl.java View source code |
//~ Methods ---------------------------------------------------------------
public Object resolveVariable(FacesContext facesContext, String name) {
if ((name == null) || (name.length() == 0)) {
throw new ReferenceSyntaxException("Varible name is null or empty");
}
// Implicit objects
Object implicitObject = _implicitObjects.get(name);
if (implicitObject != null) {
if (implicitObject instanceof ImplicitObject) {
// a complex runtime object
return ((ImplicitObject) implicitObject).get(facesContext);
} else {
// a simple object
return implicitObject;
}
}
ExternalContext externalContext = facesContext.getExternalContext();
// Request context
Map requestMap = externalContext.getRequestMap();
Object obj = requestMap.get(name);
if (obj != null) {
return obj;
}
// Session context
obj = externalContext.getSessionMap().get(name);
if (obj != null) {
return obj;
}
// Application context
obj = externalContext.getApplicationMap().get(name);
if (obj != null) {
return obj;
}
// ManagedBean
ManagedBean mbc = getRuntimeConfig(facesContext).getManagedBean(name);
if (mbc != null) {
// check for cyclic references
List beansUnderConstruction = (List) requestMap.get(BEANS_UNDER_CONSTRUCTION);
if (beansUnderConstruction == null) {
beansUnderConstruction = new ArrayList();
requestMap.put(BEANS_UNDER_CONSTRUCTION, beansUnderConstruction);
}
String managedBeanName = mbc.getManagedBeanName();
if (beansUnderConstruction.contains(managedBeanName)) {
throw new FacesException("Detected cyclic reference to managedBean " + mbc.getManagedBeanName());
}
beansUnderConstruction.add(managedBeanName);
try {
obj = beanBuilder.buildManagedBean(facesContext, mbc);
} finally {
beansUnderConstruction.remove(managedBeanName);
}
// put in scope
String scopeKey = mbc.getManagedBeanScope();
// find the scope handler object
Scope scope = (Scope) _scopes.get(scopeKey);
if (scope == null) {
log.error("Managed bean '" + name + "' has illegal scope: " + scopeKey);
} else {
scope.put(externalContext, name, obj);
}
if (obj == null && log.isDebugEnabled()) {
log.debug("Variable '" + name + "' could not be resolved.");
}
return obj;
}
if (log.isDebugEnabled()) {
log.debug("Variable '" + name + "' could not be resolved.");
}
return null;
}
Example 33
Project: primefaces-extensions-master File: RemoteCommandRenderer.java View source code |
protected String buildAjaxRequest(final FacesContext context, final AjaxSource source, final List<RemoteCommandParameter> parameters) {
final UIComponent component = (UIComponent) source;
final String clientId = component.getClientId(context);
final UIComponent form = ComponentUtils.findParentForm(context, component);
if (form == null) {
throw new FacesException("Component " + component.getClientId(context) + " must be enclosed in a form.");
}
final StringBuilder req = new StringBuilder();
req.append("PrimeFaces.ab(");
//form
req.append("{formId:").append("'").append(form.getClientId(context)).append("'");
//source
req.append(",source:").append("'").append(clientId).append("'");
//process
String process = source.getProcess();
if (process == null) {
process = "@all";
} else {
process = ComponentUtils.findClientIds(context, component, process);
//add @this
if (process.indexOf(clientId) == -1) {
process = process + " " + clientId;
}
}
req.append(",process:'").append(process).append("'");
//update
if (source.getUpdate() != null) {
req.append(",update:'");
req.append(ComponentUtils.findClientIds(context, component, source.getUpdate()));
req.append("'");
}
//async
if (source.isAsync()) {
req.append(",async:true");
}
//global
if (!source.isGlobal()) {
req.append(",global:false");
}
//callbacks
if (source.getOnstart() != null) {
req.append(",onstart:function(){").append(source.getOnstart()).append(";}");
}
if (source.getOnerror() != null) {
req.append(",onerror:function(xhr, status, error){").append(source.getOnerror()).append(";}");
}
if (source.getOnsuccess() != null) {
req.append(",onsuccess:function(data, status, xhr){").append(source.getOnsuccess()).append(";}");
}
if (source.getOncomplete() != null) {
req.append(",oncomplete:function(xhr, status, args){").append(source.getOncomplete()).append(";}");
}
//params
req.append(",params:{");
for (int i = 0; i < parameters.size(); i++) {
if (i != 0) {
req.append(",");
}
final RemoteCommandParameter param = parameters.get(i);
req.append("\"");
req.append(clientId).append("_").append(param.getName());
req.append("\"");
req.append(":").append(param.getName());
}
req.append("}});");
return req.toString();
}
Example 34
Project: primefaces-showcase-clickstart-master File: PhotoShare.java View source code |
public void share(CaptureEvent captureEvent) {
String photo = getRandomImageName();
byte[] data = captureEvent.getData();
ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();
String newFileName = servletContext.getRealPath("") + File.separator + "photocam" + File.separator + photo + ".png";
FileImageOutputStream imageOutput;
try {
imageOutput = new FileImageOutputStream(new File(newFileName));
imageOutput.write(data, 0, data.length);
imageOutput.close();
PushContextFactory.getDefault().getPushContext().push("/photoshare", photo + ".png");
} catch (Exception e) {
throw new FacesException("Error in writing captured image.");
}
}
Example 35
Project: primefaces-showcase-master File: PhotoCamBean.java View source code |
public void oncapture(CaptureEvent captureEvent) {
String photo = getRandomImageName();
this.photos.add(0, photo);
byte[] data = captureEvent.getData();
ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();
String newFileName = servletContext.getRealPath("") + File.separator + "photocam" + File.separator + photo + ".png";
FileImageOutputStream imageOutput;
try {
imageOutput = new FileImageOutputStream(new File(newFileName));
imageOutput.write(data, 0, data.length);
imageOutput.close();
} catch (Exception e) {
throw new FacesException("Error in writing captured image.");
}
}
Example 36
Project: PrimefacesShowcase-master File: ComplexMasterDetailController.java View source code |
public String saveFailure(Person person) {
FacesContext fc = FacesContext.getCurrentInstance();
ELContext elContext = fc.getELContext();
SelectLevelListener selectLevelListener;
try {
selectLevelListener = (SelectLevelListener) elContext.getELResolver().getValue(elContext, null, "selectLevelListener");
selectLevelListener.setErrorOccured(true);
} catch (RuntimeException e) {
throw new FacesException(e.getMessage(), e);
}
FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Person " + person.getName() + " could not be saved", null);
FacesContext.getCurrentInstance().addMessage(null, message);
return null;
}
Example 37
Project: richfaces-cdk-master File: CdkClassLoaderTest.java View source code |
@Test
public void testClassLoader() throws Exception {
Iterable<File> paths = Lists.newArrayList(getLibraryFile("test.source.properties"), getLibraryFile("javax/faces/component/UIComponent.class"));
CdkClassLoader loader = new CdkClassLoader(paths, null);
Class<?> class1 = loader.loadClass("javax.faces.application.Application");
assertNotNull(loader.getResource("javax/faces/FacesException.class"));
assertNotNull(loader.getResource("org/richfaces/cdk/apt/test.html"));
assertNull(loader.getResource("javax/el/ELContext.class"));
}
Example 38
Project: smartErp-master File: PhotoShare.java View source code |
public void share(CaptureEvent captureEvent) {
String photo = getRandomImageName();
byte[] data = captureEvent.getData();
ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();
String newFileName = servletContext.getRealPath("") + File.separator + "photocam" + File.separator + photo + ".png";
FileImageOutputStream imageOutput;
try {
imageOutput = new FileImageOutputStream(new File(newFileName));
imageOutput.write(data, 0, data.length);
imageOutput.close();
RequestContext.getCurrentInstance().push("photoshare", photo + ".png");
} catch (Exception e) {
throw new FacesException("Error in writing captured image.");
}
}
Example 39
Project: spring-roo-custom-master File: ViewExpiredExceptionExceptionHandler-template.java View source code |
@Override
public void handle() throws FacesException {
for (Iterator<ExceptionQueuedEvent> i = getUnhandledExceptionQueuedEvents().iterator(); i.hasNext(); ) {
ExceptionQueuedEvent event = i.next();
ExceptionQueuedEventContext context = (ExceptionQueuedEventContext) event.getSource();
Throwable t = context.getException();
if (t instanceof ViewExpiredException) {
ViewExpiredException vee = (ViewExpiredException) t;
FacesContext facesContext = FacesContext.getCurrentInstance();
Map<String, Object> requestMap = facesContext.getExternalContext().getRequestMap();
NavigationHandler navigationHandler = facesContext.getApplication().getNavigationHandler();
try {
// Push some useful stuff to the request scope for use in the page
requestMap.put("currentViewId", vee.getViewId());
navigationHandler.handleNavigation(facesContext, null, "/viewExpired");
facesContext.renderResponse();
} finally {
i.remove();
}
}
}
// At this point, the queue will not contain any ViewExpiredEvents. Therefore, let the parent handle them.
getWrapped().handle();
}
Example 40
Project: summer-master File: HtmlView.java View source code |
protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
if (lifecycleFactory == null) {
lifecycleFactory = (LifecycleFactory) FactoryFinder.getFactory(FactoryFinder.LIFECYCLE_FACTORY);
}
FacesContextFactory facesContextFactory = (FacesContextFactory) FactoryFinder.getFactory(FactoryFinder.FACES_CONTEXT_FACTORY);
FacesContext facesContext = facesContextFactory.getFacesContext(RequestUtils.getServletContext(), request, response, lifecycleFactory.getLifecycle(LifecycleFactory.DEFAULT_LIFECYCLE));
facesContext.setCurrentPhaseId(PhaseId.RESTORE_VIEW);
facesContext.getExternalContext().getFlash().doPrePhaseActions(facesContext);
Map<String, Object> requestMap = facesContext.getExternalContext().getRequestMap();
Iterator<String> i = model.keySet().iterator();
while (i.hasNext()) {
String key = i.next().toString();
if (!requestMap.containsKey(key)) {
requestMap.put(key, model.get(key));
}
}
ViewHandler viewHandler = facesContext.getApplication().getViewHandler();
viewHandler.initView(facesContext);
UIViewRoot viewRoot = viewHandler.createView(facesContext, getUrl());
viewRoot.setLocale(RequestContextUtils.getLocale(request));
viewRoot.setTransient(true);
facesContext.setCurrentPhaseId(PhaseId.RENDER_RESPONSE);
facesContext.setViewRoot(viewRoot);
facesContext.renderResponse();
try {
facesContext.getApplication().getViewHandler().renderView(facesContext, viewRoot);
} catch (IOException e) {
throw new FacesException("An I/O error occurred during view rendering", e);
} finally {
facesContext.responseComplete();
facesContext.release();
}
}
Example 41
Project: titanic-javaee7-master File: SentinelMenuRenderer.java View source code |
protected void encodeMenuItem(FacesContext context, AbstractMenu menu, MenuItem menuitem, int marginLevel) throws IOException {
ResponseWriter writer = context.getResponseWriter();
String title = menuitem.getTitle();
boolean disabled = menuitem.isDisabled();
String style = menuitem.getStyle();
writer.startElement("a", null);
if (title != null)
writer.writeAttribute("title", title, null);
if (style != null)
writer.writeAttribute("style", style, null);
if (marginLevel > 0)
writer.writeAttribute("class", "marginLevel-" + marginLevel, null);
if (disabled) {
writer.writeAttribute("href", "#", null);
writer.writeAttribute("onclick", "return false;", null);
} else {
String onclick = menuitem.getOnclick();
if (marginLevel == 0) {
onclick = (onclick == null) ? "Sentinel.toggleSubMenu(this)" : "Sentinel.toggleSubMenu(this);" + onclick;
}
//GET
if (menuitem.getUrl() != null || menuitem.getOutcome() != null) {
String targetURL = getTargetURL(context, (UIOutcomeTarget) menuitem);
writer.writeAttribute("href", targetURL, null);
if (menuitem.getTarget() != null) {
writer.writeAttribute("target", menuitem.getTarget(), null);
}
} else //POST
{
writer.writeAttribute("href", "#", null);
UIComponent form = ComponentUtils.findParentForm(context, menu);
if (form == null) {
throw new FacesException("MenuItem must be inside a form element");
}
String command;
if (menuitem.isDynamic()) {
String menuClientId = menu.getClientId(context);
Map<String, List<String>> params = menuitem.getParams();
if (params == null) {
params = new LinkedHashMap<String, List<String>>();
}
List<String> idParams = new ArrayList<String>();
idParams.add(menuitem.getId());
params.put(menuClientId + "_menuid", idParams);
command = menuitem.isAjax() ? buildAjaxRequest(context, menu, (AjaxSource) menuitem, form, params) : buildNonAjaxRequest(context, menu, form, menuClientId, params, true);
} else {
command = menuitem.isAjax() ? buildAjaxRequest(context, (AjaxSource) menuitem, form) : buildNonAjaxRequest(context, ((UIComponent) menuitem), form, ((UIComponent) menuitem).getClientId(context), true);
}
onclick = (onclick == null) ? command : onclick + ";" + command;
}
if (onclick != null) {
writer.writeAttribute("onclick", onclick, null);
}
}
encodeMenuItemContent(context, menu, menuitem);
writer.endElement("a");
}
Example 42
Project: arquillian-extension-portal-master File: PortletFacesContextFactoryWrapper.java View source code |
public FacesContext getFacesContext(Object context, Object request, Object response, Lifecycle lifecycle) throws FacesException {
FacesContext facesContext = new WrappedFacesContext(delegate.getFacesContext(context, request, response, lifecycle));
if (request instanceof PortletRequest) {
PortletRequest portletReq = (PortletRequest) request;
facesContext.getAttributes().put(FacesContextFactoryWrapper.WARP_ENABLED, Boolean.FALSE);
try {
LifecycleManager manager = LifecycleManagerStore.get(PortletRequest.class, portletReq);
manager.bindTo(FacesContext.class, facesContext);
facesContext.getAttributes().put(FacesContextFactoryWrapper.WARP_ENABLED, Boolean.TRUE);
manager.fireEvent(new FacesContextInitialized(facesContext));
} catch (ObjectNotAssociatedException e) {
log.fine("no association of manager found for this PortletRequest");
} catch (ObjectAlreadyAssociatedException e) {
throw new IllegalStateException(e);
}
}
return facesContext;
}
Example 43
Project: BuildAndTestPattern4Xpages-master File: UITestsuite.java View source code |
@Override
public void processAjaxRequest(FacesContext context) throws IOException {
HttpServletResponse httpResponse = (HttpServletResponse) context.getExternalContext().getResponse();
// We mark it as committed and use its delegate instead
if (httpResponse instanceof XspHttpServletResponse) {
XspHttpServletResponse r = (XspHttpServletResponse) httpResponse;
r.setCommitted(true);
httpResponse = r.getDelegate();
}
try {
XSPTestSuite testsuite = XSPTestRunner.testClassesAsSuite(getAllTestClasses());
ByteArrayOutputStream out = TestSuiteXMLProducer.INSTANCE.buildXMLStream(testsuite);
httpResponse.setContentType("application/xml");
httpResponse.addHeader("Content-disposition", "filename=\"" + getDownloadFile() + "\"");
out.writeTo(httpResponse.getOutputStream());
out.close();
httpResponse.getOutputStream().close();
} catch (Exception ex) {
throw new FacesException("Error generationg file.", ex);
}
}
Example 44
Project: components-master File: BeanValidatorServiceImpl.java View source code |
public Collection<String> validateExpression(FacesContext context, ValueExpression expression, Object newValue, Class<?>... groups) { if (null == context) { throw new FacesException(INPUT_PARAMETERS_IS_NOT_CORRECT); } Collection<String> validationMessages = null; if (null != expression) { ValueDescriptor valueDescriptor; try { valueDescriptor = analayser.updateValueAndGetPropertyDescriptor(context, expression, newValue); } catch (ELException e) { throw new FacesException(e); } if (valueDescriptor != null) { validationMessages = validate(context, valueDescriptor.getBeanType(), valueDescriptor.getName(), newValue, groups); } } if (validationMessages == null) { validationMessages = Collections.emptySet(); } return validationMessages; }
Example 45
Project: deface-master File: MockApplication12.java View source code |
/** {@inheritDoc} */
public UIComponent createComponent(ValueExpression expression, FacesContext context, String componentType) {
UIComponent component = null;
try {
component = (UIComponent) expression.getValue(context.getELContext());
if (component == null) {
component = createComponent(componentType);
expression.setValue(context.getELContext(), component);
}
} catch (Exception e) {
throw new FacesException(e);
}
return component;
}
Example 46
Project: glassfish-master File: MenuTreeRenderer.java View source code |
public void encodeEnd(FacesContext context, UIComponent component) throws IOException { Graph graph = null; // Acquire the root node of the graph representing the menu graph = (Graph) ((GraphComponent) component).getValue(); if (graph == null) { throw new FacesException("Graph could not be located"); } Node root = graph.getRoot(); if (root == null) { throw new FacesException("Graph has no root node"); } if (root.getChildCount() < 1) { // Nothing to render return; } this.component = component; this.context = context; clientId = component.getClientId(context); imageLocation = getImagesLocation(context); treeClass = (String) component.getAttributes().get("graphClass"); selectedClass = (String) component.getAttributes().get("selectedClass"); unselectedClass = (String) component.getAttributes().get("unselectedClass"); ResponseWriter writer = context.getResponseWriter(); writer.write("<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\""); if (treeClass != null) { writer.write(" class=\""); writer.write(treeClass); writer.write("\""); } writer.write(">"); writer.write("\n"); int level = 0; encodeNode(writer, root, level, root.getDepth(), true); writer.write("<input type=\"hidden\" name=\"" + clientId + "\" />"); writer.write("</table>"); writer.write("\n"); }
Example 47
Project: hdiv-master File: OutputLinkComponentProcessor.java View source code |
public void processOutputLink(final FacesContext context, final HtmlOutputLink component) {
try {
ExternalContext externalContext = context.getExternalContext();
HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();
String url = component.getValue().toString();
RequestContextHolder requestContext = HDIVUtil.getRequestContext(request);
String hdivParameter = requestContext.getHdivParameterName();
UrlData urlData = linkUrlProcessor.createUrlData(url, Method.GET, hdivParameter, requestContext);
if (urlData.isHdivStateNecessary(config)) {
boolean hasUIParams = UtilsJsf.hasUIParameterChild(component);
// if url hasn't got parameters, we do not have to include HDIV's state
if (!config.isValidationInUrlsWithoutParamsActivated() && !urlData.containsParams() && !hasUIParams) {
// Do nothing
return;
}
IDataComposer dataComposer = HDIVUtil.getRequestContext(request).getDataComposer();
dataComposer.beginRequest(Method.GET, urlData.getUrlWithoutContextPath());
urlData.setComposedUrlParams(dataComposer.composeParams(urlData.getUrlParams(), Method.GET, Constants.ENCODING_UTF_8));
if (hasUIParams) {
for (UIComponent comp : component.getChildren()) {
if (comp instanceof UIParameter) {
UIParameter param = (UIParameter) comp;
String name = param.getName();
String value = param.getValue().toString();
dataComposer.compose(name, value, false);
}
}
String stateParam = dataComposer.endRequest();
url = linkUrlProcessor.getProcessedUrl(dataComposer.getBuilder(), urlData);
component.setValue(url);
// Add a children UIParam component with Hdiv's state
UIParameter paramComponent = (UIParameter) context.getApplication().createComponent(UIParameter.COMPONENT_TYPE);
paramComponent.setName(hdivParameter);
paramComponent.setValue(stateParam);
component.getChildren().add(paramComponent);
} else {
String stateParam = dataComposer.endRequest();
// Add state directly in the outputLink's value
url = linkUrlProcessor.getProcessedUrlWithHdivState(dataComposer.getBuilder(), hdivParameter, urlData, stateParam);
component.setValue(url);
}
}
} catch (FacesException e) {
log.error("Error in OutputLinkComponentProcessor.processOutputLink: " + e.getMessage());
throw e;
}
}
Example 48
Project: javablog-master File: RestoreViewInterceptor.java View source code |
/**
* Restore View (JSF.2.2.1)
*
* @param viewId
* The view id
* @param facesContext
* The faces context
* @return true, if immediate rendering should occur
*/
protected boolean executePhase(String viewId, FacesContext facesContext) {
boolean skipFurtherProcessing = false;
if (log.isTraceEnabled())
log.trace("entering restoreView");
informPhaseListenersBefore(facesContext, PhaseId.RESTORE_VIEW);
try {
if (isResponseComplete(facesContext, "restoreView", true)) {
// have to skips this phase
return true;
}
if (shouldRenderResponse(facesContext, "restoreView", true)) {
skipFurtherProcessing = true;
}
ExternalContext externalContext = facesContext.getExternalContext();
String defaultSuffix = externalContext.getInitParameter(ViewHandler.DEFAULT_SUFFIX_PARAM_NAME);
String suffix = defaultSuffix != null ? defaultSuffix : ViewHandler.DEFAULT_SUFFIX;
if (viewId != null) {
viewId += suffix;
}
if (viewId == null) {
if (!externalContext.getRequestServletPath().endsWith("/")) {
try {
externalContext.redirect(externalContext.getRequestServletPath() + "/");
facesContext.responseComplete();
return true;
} catch (IOException e) {
throw new FacesException("redirect failed", e);
}
}
}
Application application = facesContext.getApplication();
ViewHandler viewHandler = application.getViewHandler();
// boolean viewCreated = false;
UIViewRoot viewRoot = viewHandler.restoreView(facesContext, viewId);
if (viewRoot == null) {
viewRoot = viewHandler.createView(facesContext, viewId);
viewRoot.setViewId(viewId);
facesContext.renderResponse();
// viewCreated = true;
}
facesContext.setViewRoot(viewRoot);
if (facesContext.getExternalContext().getRequestParameterMap().isEmpty()) {
// no POST or query parameters --> set render response flag
facesContext.renderResponse();
}
recursivelyHandleComponentReferencesAndSetValid(facesContext, viewRoot);
} finally {
informPhaseListenersAfter(facesContext, PhaseId.RESTORE_VIEW);
}
if (isResponseComplete(facesContext, "restoreView", false) || shouldRenderResponse(facesContext, "restoreView", false)) {
// since this phase is completed we don't need to return right away
// even if the response is completed
skipFurtherProcessing = true;
}
if (!skipFurtherProcessing && log.isTraceEnabled())
log.trace("exiting restoreView ");
return skipFurtherProcessing;
}
Example 49
Project: javahaiku-master File: RestoreViewInterceptor.java View source code |
/**
* Restore View (JSF.2.2.1)
*
* @param viewId
* The view id
* @param facesContext
* The faces context
* @return true, if immediate rendering should occur
*/
protected boolean executePhase(String viewId, FacesContext facesContext) {
boolean skipFurtherProcessing = false;
if (log.isTraceEnabled())
log.trace("entering restoreView");
informPhaseListenersBefore(facesContext, PhaseId.RESTORE_VIEW);
try {
if (isResponseComplete(facesContext, "restoreView", true)) {
// have to skips this phase
return true;
}
if (shouldRenderResponse(facesContext, "restoreView", true)) {
skipFurtherProcessing = true;
}
ExternalContext externalContext = facesContext.getExternalContext();
String defaultSuffix = externalContext.getInitParameter(ViewHandler.DEFAULT_SUFFIX_PARAM_NAME);
String suffix = defaultSuffix != null ? defaultSuffix : ViewHandler.DEFAULT_SUFFIX;
if (viewId != null) {
viewId += suffix;
}
if (viewId == null) {
if (!externalContext.getRequestServletPath().endsWith("/")) {
try {
externalContext.redirect(externalContext.getRequestServletPath() + "/");
facesContext.responseComplete();
return true;
} catch (IOException e) {
throw new FacesException("redirect failed", e);
}
}
}
Application application = facesContext.getApplication();
ViewHandler viewHandler = application.getViewHandler();
// boolean viewCreated = false;
UIViewRoot viewRoot = viewHandler.restoreView(facesContext, viewId);
if (viewRoot == null) {
viewRoot = viewHandler.createView(facesContext, viewId);
viewRoot.setViewId(viewId);
facesContext.renderResponse();
// viewCreated = true;
}
facesContext.setViewRoot(viewRoot);
if (facesContext.getExternalContext().getRequestParameterMap().isEmpty()) {
// no POST or query parameters --> set render response flag
facesContext.renderResponse();
}
recursivelyHandleComponentReferencesAndSetValid(facesContext, viewRoot);
} finally {
informPhaseListenersAfter(facesContext, PhaseId.RESTORE_VIEW);
}
if (isResponseComplete(facesContext, "restoreView", false) || shouldRenderResponse(facesContext, "restoreView", false)) {
// since this phase is completed we don't need to return right away
// even if the response is completed
skipFurtherProcessing = true;
}
if (!skipFurtherProcessing && log.isTraceEnabled())
log.trace("exiting restoreView ");
return skipFurtherProcessing;
}
Example 50
Project: jsfexporter-master File: DataExporter.java View source code |
private <TS extends UIComponent, CS, TT, CT> void internalProcessAction(ActionEvent event) throws Exception {
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext = facesContext.getExternalContext();
ELContext elContext = facesContext.getELContext();
// get the export source and retrieve source options
String componentId = (String) source.getValue(elContext);
TS sourceComponent = (TS) event.getComponent().findComponent(componentId);
if (sourceComponent == null) {
throw new FacesException("Could not find component \"" + componentId + "\" in view");
}
IExportSource<TS, CS> exportSource = (IExportSource<TS, CS>) ExportSourceFactory.getExportSource(facesContext, sourceComponent);
CS sourceOptionsValue;
if (// source options are not mandatory; get the defaults if not set
sourceOptions == null) {
sourceOptionsValue = exportSource.getDefaultConfigOptions();
} else {
sourceOptionsValue = (CS) sourceOptions.getValue(elContext);
}
// get the export type factory and retrieve file options
String fileTypeValue = (String) fileType.getValue(elContext);
IExportTypeFactory<TT, CT, ?> exportTypeFactory = (IExportTypeFactory<TT, CT, ?>) ExportTypeFactoryFactory.getExportType(facesContext, fileTypeValue);
CT fileOptionsValue;
if (// file options are not mandatory; get the defaults if not set
fileOptions == null) {
fileOptionsValue = exportTypeFactory.getDefaultConfigOptions();
} else {
fileOptionsValue = (CT) fileOptions.getValue(elContext);
}
// create a new exporter
IExportType<TT, CT, ?> exportType = exportTypeFactory.createNewExporter(fileOptionsValue);
TT exportContext = exportType.getContext();
// invoke the pre-processor if there is one
if (preProcessor != null) {
preProcessor.invoke(elContext, new Object[] { exportContext });
}
// generate the export
exportType.beginExport(exportSource.getColumnCount(sourceComponent, sourceOptionsValue));
exportSource.exportData(sourceComponent, sourceOptionsValue, exportType, facesContext);
exportType.endExport();
// invoke the post-processor if there is one
if (postProcessor != null) {
postProcessor.invoke(elContext, new Object[] { exportContext });
}
// configure response meta-data
externalContext.setResponseContentType(exportType.getContentType());
externalContext.setResponseHeader("Expires", "0");
externalContext.setResponseHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
externalContext.setResponseHeader("Pragma", "public");
/*
* filename* is the proper way to send non-ASCII filenames, but not all browsers support it (e.g. IE 8).
* So we also supply a normal filename encoded the same way, since that works on most browsers (but not Firefox).
* See RFC 6266 and http://greenbytes.de/tech/tc2231/
*/
String encodedFileName = URLEncoder.encode(fileName.getValue(elContext) + "." + exportType.getFileExtension(), "UTF-8");
externalContext.setResponseHeader("Content-Disposition", "attachment; filename=\"" + encodedFileName + "\"; filename*=UTF8''" + encodedFileName);
// write the response and signal JSF that we're done
exportType.writeExport(externalContext);
facesContext.responseComplete();
}
Example 51
Project: jsfunit-master File: SimpleTreeBean.java View source code |
private void loadTree() {
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext = facesContext.getExternalContext();
InputStream dataStream = externalContext.getResourceAsStream(DATA_PATH);
try {
Properties properties = new Properties();
properties.load(dataStream);
rootNode = new TreeNodeImpl();
addNodes(null, rootNode, properties);
} catch (IOException e) {
throw new FacesException(e.getMessage(), e);
} finally {
if (dataStream != null) {
try {
dataStream.close();
} catch (IOException e) {
externalContext.log(e.getMessage(), e);
}
}
}
}
Example 52
Project: liferay-newsletter-master File: WcsExceptionHandler.java View source code |
@Override
public void handle() throws FacesException {
Iterable<ExceptionQueuedEvent> events = this.wrapped.getUnhandledExceptionQueuedEvents();
for (Iterator<ExceptionQueuedEvent> it = events.iterator(); it.hasNext(); ) {
ExceptionQueuedEvent event = it.next();
ExceptionQueuedEventContext eqec = event.getContext();
System.out.println("eqec.getException()" + eqec.getException());
if (eqec.getException() instanceof ViewExpiredException || eqec.getException() instanceof AbortProcessingException) {
FacesContext context = eqec.getContext();
NavigationHandler navHandler = context.getApplication().getNavigationHandler();
try {
navHandler.handleNavigation(context, null, "main.xhtml?faces-redirect=true&expired=true");
} catch (Exception e) {
System.out.println("exp" + e);
} finally {
it.remove();
}
}
}
this.wrapped.handle();
;
}
Example 53
Project: nuxeo-jsf-master File: CompositionHandler.java View source code |
/*
* (non-Javadoc)
* @see
* com.sun.facelets.FaceletHandler#apply(com.sun.facelets.FaceletContext,
* javax.faces.component.UIComponent)
*/
@Override
public void apply(FaceletContext ctxObj, UIComponent parent) throws IOException, FacesException, FaceletException, ELException {
FaceletContextImplBase ctx = (FaceletContextImplBase) ctxObj;
VariableMapper orig = ctx.getVariableMapper();
if (this.params != null) {
VariableMapper vm = new VariableMapperWrapper(orig);
ctx.setVariableMapper(vm);
for (int i = 0; i < this.params.length; i++) {
this.params[i].apply(ctx, parent);
}
}
ctx.extendClient(this);
try {
final FacesContext facesContext = ctx.getFacesContext();
// Get the negotiation strategy
final ExternalContext external = facesContext.getExternalContext();
final Map<String, Object> requestMap = external.getRequestMap();
final String root = external.getRequestContextPath();
final ApplicationType application = (ApplicationType) Manager.getTypeRegistry().lookup(TypeFamily.APPLICATION, root);
String strategy = null;
if (application != null) {
final NegotiationDef negotiation = application.getNegotiation();
if (negotiation != null) {
requestMap.put("org.nuxeo.theme.default.theme", negotiation.getDefaultTheme());
requestMap.put("org.nuxeo.theme.default.engine", negotiation.getDefaultEngine());
requestMap.put("org.nuxeo.theme.default.perspective", negotiation.getDefaultPerspective());
strategy = negotiation.getStrategy();
}
}
// override startegy if defined
if (strategyAttribute != null) {
strategy = strategyAttribute.getValue(ctx);
}
String contextPath = BaseURL.getContextPath();
if (strategy == null) {
log.error("Could not obtain the negotiation strategy for " + root);
external.redirect(contextPath + "/nxthemes/error/negotiationStrategyNotSet.faces");
} else {
try {
final String spec = new JSFNegotiator(strategy, facesContext, (HttpServletRequest) external.getRequest()).getSpec();
final URL themeUrl = new URL(spec);
requestMap.put("org.nuxeo.theme.url", themeUrl);
ctx.includeFacelet(parent, themeUrl);
} catch (NegotiationException e) {
log.error("Could not get default negotiation settings.", e);
external.redirect(contextPath + "/nxthemes/error/negotiationDefaultValuesNotSet.faces");
}
}
} finally {
ctx.popClient(this);
ctx.setVariableMapper(orig);
}
}
Example 54
Project: nuxeo-master File: RepeatTagHandler.java View source code |
/**
* Encapsulate the call to a c:forEach tag in an SetTagHandler exposing the value and making sure the tagConfigId
* changes when the value changes (see NXP-11434).
* <p>
* See also NXP-15050: since 6.0, anchor handler in component tree to ensure proper ajax refresh when iteration
* value changes.
*/
@Override
public void apply(FaceletContext ctx, UIComponent parent) throws IOException, FacesException, FaceletException, ELException {
String anchor = String.valueOf(true);
FaceletHandler nextHandler = this.nextHandler;
TagAttribute varStatusAttr = varStatus;
if (index != null) {
// wrap the next handler in a set tag handler to expose the index
// value from the varStatus attribute.
String indexValue = index.getValue(ctx);
if (!StringUtils.isBlank(indexValue)) {
String varStatusValue = varStatus != null ? varStatus.getValue(ctx) : null;
if (StringUtils.isBlank(varStatusValue)) {
// need to create and set it as an attribute for the index
// to be exposed
varStatusAttr = createAttribute(config, "varStatus", getVarName(indexValue + "_varStatus"));
} else {
varStatusAttr = createAttribute(config, "varStatus", varStatusValue);
}
ComponentConfig indexVarConfig = TagConfigFactory.createAliasTagConfig(config, tagId, indexValue, "#{" + varStatusAttr.getValue() + ".index}", "false", anchor, this.nextHandler);
nextHandler = new SetTagHandler(indexVarConfig);
}
}
FaceletHandler handler;
if (renderTime(ctx)) {
List<TagAttribute> repeatAttrs = new ArrayList<TagAttribute>();
TagAttribute itemsAttr = getItemsAttribute();
repeatAttrs.add(createAttribute(config, "value", itemsAttr != null ? itemsAttr.getValue() : null));
repeatAttrs.addAll(copyAttributes(config, id, var, begin, end, step, varStatusAttr, tranzient));
ComponentConfig repeatConfig = TagConfigFactory.createComponentConfig(config, tagId, new TagAttributesImpl(repeatAttrs.toArray(new TagAttribute[] {})), nextHandler, UIRepeat.COMPONENT_TYPE, null);
handler = new ComponentHandler(repeatConfig);
} else {
List<TagAttribute> forEachAttrs = new ArrayList<TagAttribute>();
forEachAttrs.add(createAttribute(config, "items", "#{" + getVarName("items") + "}"));
forEachAttrs.addAll(copyAttributes(config, var, begin, end, step, varStatusAttr, tranzient));
TagConfig forEachConfig = TagConfigFactory.createTagConfig(config, tagId, new TagAttributesImpl(forEachAttrs.toArray(new TagAttribute[] {})), nextHandler);
ForEachHandler forEachHandler = new ForEachHandler(forEachConfig);
String setTagConfigId = getTagConfigId(ctx);
TagAttribute itemsAttr = getItemsAttribute();
ComponentConfig aliasConfig = TagConfigFactory.createAliasTagConfig(config, setTagConfigId, getVarName("items"), itemsAttr != null ? itemsAttr.getValue() : null, "false", anchor, forEachHandler);
handler = new SetTagHandler(aliasConfig);
}
// apply
handler.apply(ctx, parent);
}
Example 55
Project: org.openntf.domino-master File: XspOpenLogPhaseListener.java View source code |
/** * This is getting VERY complex because of the variety of exceptions and tracking up the stack trace to find the right class to get as * much info as possible. Extracted into a separate method to make it more readable. * * @param r * requestScope map */ private void processUncaughtException(final Map<String, Object> r) { // requestScope.error is not null, we're on the custom error page. Object error = r.get("error"); // Set the agent (page we're on) to the *previous* page XspOpenLogUtil.getXspOpenLogItem().setThisAgent(false); String msg = ""; if ("com.ibm.xsp.exception.EvaluationExceptionEx".equals(error.getClass().getName())) { // EvaluationExceptionEx, so SSJS error is on a component property. // Hit by ErrorOnLoad.xsp EvaluationExceptionEx ee = (EvaluationExceptionEx) error; if ("com.ibm.jscript.InterpretException".equals(ee.getCause().getClass().getName())) { InterpretException ie = (InterpretException) ee.getCause(); msg = "Error on " + ee.getErrorComponentId() + " " + ee.getErrorPropertyId() + " property/event, line " + Integer.toString(ie.getErrorLine()) + ":\n\n" + ie.getLocalizedMessage() + "\n\n" + ie.getExpressionText(); } else if ("com.ibm.jscript.parser.ParseException".equals(ee.getCause().getClass().getName())) { ParseException ie = (ParseException) ee.getCause(); msg = "Error on " + ee.getErrorComponentId() + " " + ee.getErrorPropertyId() + " property/event " + ":\n\n" + ie.getLocalizedMessage(); } XspOpenLogUtil.getXspOpenLogItem().logErrorEx(ee, msg, null, null); } else if ("javax.faces.FacesException".equals(error.getClass().getName())) { // FacesException, so error is on event or method in EL FacesException fe = (FacesException) error; InterpretException ie = null; EvaluationExceptionEx ee = null; msg = "Error on "; try { // javax.faces.el.MethodNotFoundException hit by ErrorOnMethod.xsp if (!"javax.faces.el.MethodNotFoundException".equals(fe.getCause().getClass().getName())) { if ("com.ibm.xsp.exception.EvaluationExceptionEx".equals(fe.getCause().getClass().getName())) { // Hit by ErrorOnClick.xsp ee = (EvaluationExceptionEx) fe.getCause(); } else if ("javax.faces.el.PropertyNotFoundException".equals(fe.getCause().getClass().getName())) { // Property not found exception, so error is on a component property msg = "PropertyNotFoundException Error, cannot locate component:\n\n"; } else if ("com.ibm.xsp.exception.EvaluationExceptionEx".equals(fe.getCause().getCause().getClass().getName())) { // Hit by using e.g. currentDocument.isNewDoc() // i.e. using a Variable that relates to a valid Java object but a method that doesn't exist ee = (EvaluationExceptionEx) fe.getCause().getCause(); } if (null != ee) { msg = msg + ee.getErrorComponentId() + " " + ee.getErrorPropertyId() + " property/event:\n\n"; if ("com.ibm.jscript.InterpretException".equals(ee.getCause().getClass().getName())) { ie = (InterpretException) ee.getCause(); } } } } catch (Throwable t) { msg = "Unexpected error class: " + fe.getCause().getClass().getName() + "\n Message recorded is: "; } if (null != ie) { msg = msg + Integer.toString(ie.getErrorLine()) + ":\n\n" + ie.getLocalizedMessage() + "\n\n" + ie.getExpressionText(); } else { msg = msg + fe.getCause().getLocalizedMessage(); } XspOpenLogUtil.getXspOpenLogItem().logErrorEx(fe.getCause(), msg, null, null); } else if ("com.ibm.xsp.FacesExceptionEx".equals(error.getClass().getName())) { // FacesException, so error is on event - doesn't get hit in examples. Can this still get hit?? FacesExceptionEx fe = (FacesExceptionEx) error; try { if ("lotus.domino.NotesException".equals(fe.getCause().getClass().getName())) { // sometimes the cause is a NotesException NotesException ne = (NotesException) fe.getCause(); msg = msg + "NotesException - " + Integer.toString(ne.id) + " " + ne.text; } else if ("java.io.IOException".equals(error.getClass().getName())) { IOException e = (IOException) error; msg = "Java IO:" + error.toString(); XspOpenLogUtil.getXspOpenLogItem().logErrorEx(e.getCause(), msg, null, null); } else { EvaluationExceptionEx ee = (EvaluationExceptionEx) fe.getCause(); InterpretException ie = (InterpretException) ee.getCause(); msg = "Error on " + ee.getErrorComponentId() + " " + ee.getErrorPropertyId() + " property/event:\n\n" + Integer.toString(ie.getErrorLine()) + ":\n\n" + ie.getLocalizedMessage() + "\n\n" + ie.getExpressionText(); } } catch (Throwable t) { try { msg = "Unexpected error class: " + fe.getCause().getClass().getName() + "\n Message recorded is: " + fe.getCause().getLocalizedMessage(); } catch (Throwable ee) { msg = fe.getLocalizedMessage(); } } XspOpenLogUtil.getXspOpenLogItem().logErrorEx(fe.getCause(), msg, null, null); } else if ("javax.faces.el.PropertyNotFoundException".equals(error.getClass().getName())) { // Hit by ErrorOnProperty.xsp // Property not found exception, so error is on a component property PropertyNotFoundException pe = (PropertyNotFoundException) error; msg = "PropertyNotFoundException Error, cannot locate component:\n\n" + pe.getLocalizedMessage(); XspOpenLogUtil.getXspOpenLogItem().logErrorEx(pe, msg, null, null); } else { try { System.out.println("Error type not found:" + error.getClass().getName()); msg = error.toString(); XspOpenLogUtil.getXspOpenLogItem().logErrorEx((Throwable) error, msg, null, null); } catch (Throwable t) { t.printStackTrace(); } } }
Example 56
Project: proudcase-master File: ProudcaseExceptionHandler.java View source code |
@Override
public void handle() throws FacesException {
// iterate through all queued exceptions
final Iterator<ExceptionQueuedEvent> i = getUnhandledExceptionQueuedEvents().iterator();
while (i.hasNext()) {
// Get the next and the source
ExceptionQueuedEvent event = i.next();
ExceptionQueuedEventContext context = (ExceptionQueuedEventContext) event.getSource();
// get the real exception
Throwable t = context.getException();
t.printStackTrace();
// we need this for navigation
final FacesContext fc = FacesContext.getCurrentInstance();
final NavigationHandler nav = fc.getApplication().getNavigationHandler();
try {
String outputMessage = "";
// view expired?
if (t instanceof ViewExpiredException) {
outputMessage = PropertyReader.getMessageResourceString(fc.getApplication().getMessageBundle(), "error_viewexpired", null, fc.getViewRoot().getLocale());
// add the error message
fc.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "", outputMessage));
}
// navigate to error page
nav.handleNavigation(fc, null, ENavigation.ERROR.toString());
fc.renderResponse();
} finally {
//remove it from queue
i.remove();
}
}
getWrapped().handle();
}
Example 57
Project: resin-master File: ManagedBeanELResolver.java View source code |
@Override
public Object getValue(ELContext env, Object base, Object property) {
if (base == null && property instanceof String) {
String key = property.toString();
ManagedBeanConfig managedBean = _managedBeanMap.get(key);
if (managedBean != null) {
env.setPropertyResolved(true);
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext extContext = facesContext.getExternalContext();
Map requestMap = extContext.getRequestMap();
Object value = requestMap.get(key);
if (value != null)
return value;
value = extContext.getSessionMap().get(key);
if (value != null)
return value;
value = extContext.getApplicationMap().get(key);
if (value != null)
return value;
Scope oldScope = (Scope) env.getContext(Scope.class);
Scope scope = oldScope;
if (scope == null) {
scope = new Scope();
env.putContext(Scope.class, scope);
}
int oldScopeValue = scope.getScope();
try {
if (scope.containsBean(key))
throw new FacesException(L.l("'{0}' is a circular managed bean reference.", key));
scope.addBean(key);
return managedBean.create(facesContext, scope);
} finally {
scope.removeBean(key);
scope.setScope(oldScopeValue);
env.putContext(Scope.class, oldScope);
}
}
}
return null;
}
Example 58
Project: richfaces-qa-master File: TemplatesListConverter.java View source code |
/**
* {@inheritDoc}
*/
public Object getAsObject(FacesContext context, UIComponent component, String value) {
try {
TemplatesList list = new TemplatesList();
for (String template : value.split(TemplatesList.ITEMS_SEPARATOR_WEB)) {
list.add(Template.valueFrom(template));
}
return list;
} catch (IllegalArgumentException iae) {
throw new FacesException("Cannot convert parameter \"" + value + "\" to the list of templates.", iae);
}
}
Example 59
Project: softwaremill-common-master File: TransactionPhaseListener.java View source code |
private void startTransaction(FacesContext facesContext) {
try {
UserTransaction utx = getUserTransaction();
if (utx.getStatus() != Status.STATUS_ACTIVE) {
utx.begin();
facesContext.getAttributes().put(STARTED_TX_KEY, new Object());
}
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new FacesException(e);
}
}
Example 60
Project: spring4-sandbox-master File: DefaultExceptionHandler.java View source code |
@Override public void handle() throws FacesException { log.debug("invoking custom ExceptionHandlder..."); Iterator<ExceptionQueuedEvent> events = getUnhandledExceptionQueuedEvents().iterator(); while (events.hasNext()) { ExceptionQueuedEvent event = events.next(); ExceptionQueuedEventContext context = (ExceptionQueuedEventContext) event.getSource(); Throwable t = context.getException(); log.debug("Exception@" + t); log.debug("ExceptionHandlder began."); log.debug("t instanceof FacesException@" + (t instanceof FacesException)); log.debug("t instanceof FacesFileNotFoundException@" + (t instanceof FacesFileNotFoundException)); if (t instanceof ViewExpiredException) { try { handleViewExpiredException((ViewExpiredException) t); } finally { events.remove(); } } if (t instanceof FacesFileNotFoundException || t instanceof TaskNotFoundException) { try { handleNotFoundException((Exception) t); } finally { events.remove(); } } log.debug("ExceptionHandlder end."); getWrapped().handle(); } }
Example 61
Project: tomee-master File: TomEEFacesConfigurationProviderFactory.java View source code |
@Override
public FacesConfigurationProvider getFacesConfigurationProvider(final ExternalContext externalContext) {
FacesConfigurationProvider returnValue = (FacesConfigurationProvider) externalContext.getApplicationMap().get(FACES_CONFIGURATION_PROVIDER_INSTANCE_KEY);
if (returnValue == null) {
final ExternalContext extContext = externalContext;
try {
returnValue = resolveFacesConfigurationProviderFromService(extContext);
externalContext.getApplicationMap().put(FACES_CONFIGURATION_PROVIDER_INSTANCE_KEY, returnValue);
} catch (final ClassNotFoundExceptionNoClassDefFoundError | e) {
} catch (final InstantiationExceptionInvocationTargetException | IllegalAccessException | e) {
getLogger().log(Level.SEVERE, "", e);
} catch (final PrivilegedActionException e) {
throw new FacesException(e);
}
}
return returnValue;
}
Example 62
Project: yougi-master File: CustomExceptionHandler.java View source code |
@Override
public void handle() throws FacesException {
ExceptionQueuedEvent event;
ExceptionQueuedEventContext eventContext;
Throwable t;
for (Iterator<ExceptionQueuedEvent> i = getUnhandledExceptionQueuedEvents().iterator(); i.hasNext(); ) {
event = i.next();
eventContext = (ExceptionQueuedEventContext) event.getSource();
t = eventContext.getException();
if (t instanceof ViewExpiredException) {
ViewExpiredException vee = (ViewExpiredException) t;
FacesContext fc = FacesContext.getCurrentInstance();
NavigationHandler nav = fc.getApplication().getNavigationHandler();
try {
fc.getExternalContext().getFlash().put("currentViewId", vee.getViewId());
nav.handleNavigation(fc, null, "/login?faces-redirect=true");
fc.renderResponse();
} finally {
i.remove();
}
}
}
getWrapped().handle();
}
Example 63
Project: com.idega.content-master File: listDocuments2.java View source code |
public void setWebDavHttpURL(String path) { this.webDavHttpURL = path; try { // String uri = (String) getApplication().createMethodBinding( // "#{WebDavTree.getUri}", null) // .invoke( // javax.faces.context.FacesContext // .getCurrentInstance(), null); // ApplicationFactory factory = (ApplicationFactory) FactoryFinder.getFactory(FactoryFinder.APPLICATION_FACTORY); // ValueBinding vb = factory.getApplication().createValueBinding("#{currentRow.name}"); // MethodBinding mb = factory.getApplication().createMethodBinding("#{currentRow.handleClick}", null); // MethodBinding mb2 = factory.getApplication().createMethodBinding("#{listDocuments2.processAction}", new Class[]{javax.faces.event.ActionEvent.class}); // // String tmp = (String) mb.invoke(FacesContext.getCurrentInstance(), null); // // setNameLink(new HtmlCommandLink()); //// setDataTable1Model(new ArrayDataModel()); // // nameLink.setValueBinding("nameLink", vb); // nameLink.setAction(mb); // nameLink.setActionListener(mb2); // getDataTable1Model().setWrappedData(getDavData()); } catch (Exception e) { System.out.println("listDocuments2 Initialization Failure"); throw e instanceof javax.faces.FacesException ? (FacesException) e : new FacesException(e); } }
Example 64
Project: arquillian-extension-warp-master File: FacesContextFactory.java View source code |
public FacesContext getFacesContext(Object context, Object request, Object response, Lifecycle lifecycle) throws FacesException {
FacesContext facesContext = delegate.getFacesContext(context, request, response, lifecycle);
if (request instanceof HttpServletRequest) {
HttpServletRequest httpReq = (HttpServletRequest) request;
facesContext = new WarpFacesContext(facesContext);
facesContext.getAttributes().put(WARP_ENABLED, Boolean.FALSE);
try {
LifecycleManager manager = (LifecycleManager) httpReq.getAttribute(WarpCommons.WARP_REQUEST_LIFECYCLE_MANAGER_ATTRIBUTE);
if (manager == null) {
log.warning("no association of manager found for this ServletRequest");
return facesContext;
}
manager.bindTo(FacesContext.class, facesContext);
facesContext.getAttributes().put(WARP_ENABLED, Boolean.TRUE);
facesContext.getAttributes().put(WarpJSFCommons.WARP_REQUEST_LIFECYCLE_MANAGER_ATTRIBUTE, manager);
manager.fireEvent(new FacesContextInitialized(facesContext));
} catch (ObjectAlreadyAssociatedException e) {
throw new IllegalStateException(e);
}
}
return facesContext;
}
Example 65
Project: Capturador-master File: MessageBean.java View source code |
/** * <p>This method is called when this bean is initially added to * application scope. Typically, this occurs as a result of evaluating * a value binding or method binding expression, which utilizes the * managed bean facility to instantiate this bean and store it into * application scope.</p> * * <p>You may customize this method to initialize and cache application wide * data values (such as the lists of valid options for dropdown list * components), or to allocate resources that are required for the * lifetime of the application.</p> */ @Override public void init() { // Perform initializations inherited from our superclass super.init(); // *Note* - this logic should NOT be modified try { _init(); } catch (Exception e) { log("MessageBean Initialization Failure", e); throw e instanceof FacesException ? (FacesException) e : new FacesException(e); } // </editor-fold> // Perform application initialization that must complete // *after* managed components are initialized // TODO - add your own initialization code here }
Example 66
Project: com.idega.faces-master File: IWNavigationHandlerImpl.java View source code |
public void handleNavigation(FacesContext facesContext, String fromAction, String outcome) {
if (outcome == null) {
// stay on current ViewRoot
return;
}
// switch to page uri if the view id represents a builder page stored as jsp
String viewId = facesContext.getViewRoot().getViewId();
ViewManager viewManager = ViewManager.getInstance(facesContext);
ViewNode viewNode = viewManager.getViewNodeForContext(facesContext);
if (viewNode != null) {
// if viewNode is not null we have a request for an URI in the ViewNode
// structure
String pageUri = viewManager.getRequestUriWithoutContext(facesContext);
if (pageUri != null) {
// something like "/pages/test/hello/" or "/workspace/builder/"
viewId = pageUri;
}
}
Map casesMap = getNavigationCases(facesContext);
NavigationCase navigationCase = null;
List casesList = (List) casesMap.get(viewId);
if (casesList != null) {
// Exact match?
navigationCase = calcMatchingNavigationCase(casesList, fromAction, outcome);
}
if (navigationCase == null) {
// Wildcard match?
List keys = getSortedWildcardKeys();
for (int i = 0, size = keys.size(); i < size; i++) {
String fromViewId = (String) keys.get(i);
if (fromViewId.length() > 2) {
String prefix = fromViewId.substring(0, fromViewId.length() - 1);
if (viewId != null && viewId.startsWith(prefix)) {
casesList = (List) casesMap.get(fromViewId);
if (casesList != null) {
navigationCase = calcMatchingNavigationCase(casesList, fromAction, outcome);
if (navigationCase != null) {
break;
}
}
}
} else {
casesList = (List) casesMap.get(fromViewId);
if (casesList != null) {
navigationCase = calcMatchingNavigationCase(casesList, fromAction, outcome);
if (navigationCase != null) {
break;
}
}
}
}
}
if (navigationCase != null) {
if (log.isTraceEnabled()) {
log.trace("handleNavigation fromAction=" + fromAction + " outcome=" + outcome + " toViewId =" + navigationCase.getToViewId() + " redirect=" + navigationCase.isRedirect());
}
if (navigationCase.isRedirect() && (// Spec
!PortletUtil.isPortletRequest(facesContext))) {
// section
// 7.4.2
// says
// "redirects
// not
// possible"
// in
// this
// case
// for
// portlets
ExternalContext externalContext = facesContext.getExternalContext();
ViewHandler viewHandler = facesContext.getApplication().getViewHandler();
String redirectPath = viewHandler.getActionURL(facesContext, navigationCase.getToViewId());
try {
externalContext.redirect(externalContext.encodeActionURL(redirectPath));
} catch (IOException e) {
throw new FacesException(e.getMessage(), e);
}
facesContext.responseComplete();
} else {
ViewHandler viewHandler = facesContext.getApplication().getViewHandler();
// create new view
String newViewId = navigationCase.getToViewId();
UIViewRoot viewRoot = viewHandler.createView(facesContext, newViewId);
viewRoot.setViewId(newViewId);
facesContext.setViewRoot(viewRoot);
facesContext.renderResponse();
}
} else {
// no navigationcase found, stay on current ViewRoot
if (log.isTraceEnabled()) {
log.trace("handleNavigation fromAction=" + fromAction + " outcome=" + outcome + " no matching navigation-case found, staying on current ViewRoot");
}
}
}
Example 67
Project: dvn-master File: GroupServiceBean.java View source code |
public UserGroup findIpGroupUser(String remotehost) { UserGroup group = null; try { List logindomains = (List<LoginDomain>) em.createQuery("Select ld from LoginDomain ld").getResultList(); LoginDomain logindomain = null; Iterator iterator = logindomains.iterator(); while (iterator.hasNext()) { logindomain = (LoginDomain) iterator.next(); // domain name substring match if (logindomain.getIpAddress().valueOf(logindomain.getIpAddress().charAt(0)).equals("*")) { if (remotehost.indexOf(logindomain.getIpAddress().substring(1)) != -1) { group = logindomain.getUserGroup(); break; } } // integer substring match. String parseIp = new String(); String regexp = null; Pattern pattern = null; Matcher matcher = null; boolean isMatch = false; if (logindomain.getIpAddress().indexOf(".*", 0) != -1) { parseIp = logindomain.getIpAddress().replace(".*", "\\."); regexp = "^" + parseIp; pattern = Pattern.compile(regexp); matcher = pattern.matcher(remotehost); isMatch = matcher.find(); } else { parseIp = logindomain.getIpAddress(); if (parseIp.equals(remotehost)) isMatch = true; } if (isMatch) { group = logindomain.getUserGroup(); break; } } } catch (IllegalArgumentException iae) { throw new FacesException(iae); } catch (IllegalStateException ise) { throw new FacesException(ise); } finally { return group; } }
Example 68
Project: Fudan-Sakai-master File: UploadRenderer.java View source code |
public void decode(FacesContext context, UIComponent component) {
log.debug("**** decode =");
ExternalContext external = context.getExternalContext();
HttpServletRequest request = (HttpServletRequest) external.getRequest();
String clientId = component.getClientId(context);
FileItem item = (FileItem) request.getAttribute(clientId + UPLOAD);
// check if file > maxSize allowed
log.debug("clientId =" + clientId);
log.debug("fileItem =" + item);
// if (item!=null) log.debug("***UploadRender: fileItem size ="+ item.getSize());
Long maxSize = (Long) ((ServletContext) external.getContext()).getAttribute("FILEUPLOAD_SIZE_MAX");
// RU - typo. Stanford agrees, so this should be FINR
if (item != null && item.getSize() / 1000 > maxSize.intValue()) {
((ServletContext) external.getContext()).setAttribute("TEMP_FILEUPLOAD_SIZE", new Long(item.getSize() / 1000));
((EditableValueHolder) component).setSubmittedValue("SizeTooBig");
return;
}
Object target;
ValueBinding binding = component.getValueBinding("target");
if (binding != null)
target = binding.getValue(context);
else
target = component.getAttributes().get("target");
String repositoryPath = (String) ((ServletContext) external.getContext()).getAttribute("FILEUPLOAD_REPOSITORY_PATH");
log.debug("****" + repositoryPath);
if (target != null) {
//directory where file would be saved
File dir = new File(repositoryPath + target.toString());
if (!dir.exists())
dir.mkdirs();
if (item != null && !("").equals(item.getName())) {
String fullname = item.getName();
fullname = fullname.replace('\\', '/');
fullname = fullname.substring(fullname.lastIndexOf("/") + 1);
int dot_index = fullname.lastIndexOf(".");
String filename = "";
if (dot_index < 0) {
filename = fullname + "_" + (new Date()).getTime();
} else {
filename = fullname.substring(0, dot_index) + "_" + (new Date()).getTime() + fullname.substring(dot_index);
}
File file = new File(dir.getPath() + "/" + filename);
log.debug("**1. filename=" + file.getPath());
try {
item.write(file);
((EditableValueHolder) component).setSubmittedValue(file.getPath());
} catch (Exception ex) {
throw new FacesException(ex);
}
}
}
}
Example 69
Project: i18n-master File: TranslationComponent.java View source code |
@Override public void encodeEnd(FacesContext facesContext) throws IOException { if (isRendered()) { StateHelper state = getStateHelper(); String message = (String) state.eval(PropertyKeys.message); String context = (String) state.eval(PropertyKeys.context); String plural = (String) state.eval(PropertyKeys.plural); Long num = (Long) state.eval(PropertyKeys.num); if (message == null) { throw new FacesException("Message id is null"); } if (plural != null && num == null) { throw new FacesException("Message id '" + message + "' requires num parameter"); } Object[] params = getParameters(); ResourceBundle bundle = getResourceBundle(facesContext); String str = I18N.translate(bundle, context, message, plural, num == null ? 0L : num.longValue(), params); facesContext.getResponseWriter().writeText(str, null); } super.encodeEnd(facesContext); }
Example 70
Project: metadata-editor-master File: EditorExceptionHandler.java View source code |
private void handleNonAjaxException(FacesContext context) {
Iterator<ExceptionQueuedEvent> unhandledExceptionQueuedEvents = getUnhandledExceptionQueuedEvents().iterator();
if (unhandledExceptionQueuedEvents.hasNext()) {
Throwable exception = unhandledExceptionQueuedEvents.next().getContext().getException();
if (exception instanceof AbortProcessingException) {
// Let JSF handle it itself.
return;
}
// go up the exception chain to the cause
while ((exception instanceof FacesException || exception instanceof ELException) && exception.getCause() != null) {
exception = exception.getCause();
}
unhandledExceptionQueuedEvents.remove();
// put information about the exception in the log. For unhandled exceptions
// this should not already have been done.
LogUtils.logException(logger, exception.getMessage(), exception);
String viewName;
if (exception instanceof ViewExpiredException) {
viewName = "/error-pages/view-expired.xhtml";
} else if (exception instanceof EditorException) {
viewName = "/error-pages/editor-error.xhtml";
} else {
viewName = "/error-pages/server-error.xhtml";
}
ExternalContext externalContext = context.getExternalContext();
Map<String, Object> requestMap = externalContext.getRequestMap();
requestMap.put("exception", exception);
FacesContext facesContext = FacesContext.getCurrentInstance();
try {
ViewHandler viewHandler = context.getApplication().getViewHandler();
UIViewRoot viewRoot = viewHandler.createView(context, viewName);
context.setViewRoot(viewRoot);
context.getPartialViewContext().setRenderAll(true);
ViewDeclarationLanguage vdl = viewHandler.getViewDeclarationLanguage(context, viewName);
vdl.buildView(context, viewRoot);
context.getApplication().publishEvent(context, PreRenderViewEvent.class, viewRoot);
vdl.renderView(context, viewRoot);
context.responseComplete();
} catch (IOException e) {
LogUtils.logException(logger, "Failed to handled exception in non ajax request.", e);
}
facesContext.responseComplete();
}
while (unhandledExceptionQueuedEvents.hasNext()) {
// Any remaining unhandled exceptions are not interesting. First fix
// the first.
unhandledExceptionQueuedEvents.next();
unhandledExceptionQueuedEvents.remove();
}
}
Example 71
Project: omnifaces-master File: DeferredTagHandlerHelper.java View source code |
// Actions --------------------------------------------------------------------------------------------------------
/**
* Create the tag instance based on the <code>binding</code> and/or <code>instanceId</code> attribute.
* @param context The involved facelet context.
* @param tag The involved tag handler.
* @param instanceId The attribute name representing the instance ID.
* @return The created instance.
* @throws IllegalArgumentException If the <code>validatorId</code> attribute is invalid or missing while the
* <code>binding</code> attribute is also missing.
* @throws ClassCastException When <code>T</code> is of wrong type.
*/
@SuppressWarnings("unchecked")
static <T> T createInstance(FaceletContext context, DeferredTagHandler tag, String instanceId) {
ValueExpression binding = getValueExpression(context, tag, "binding", Object.class);
ValueExpression id = getValueExpression(context, tag, instanceId, String.class);
T instance = null;
if (binding != null) {
instance = (T) binding.getValue(context);
}
if (id != null) {
try {
instance = tag.create(context.getFacesContext().getApplication(), (String) id.getValue(context));
} catch (FacesException e) {
throw new IllegalArgumentException(format(ERROR_INVALID_ID, tag.getClass().getSimpleName(), instanceId, id), e);
}
if (binding != null) {
binding.setValue(context, instance);
}
} else if (instance == null) {
throw new IllegalArgumentException(format(ERROR_MISSING_ID, tag.getClass().getSimpleName(), instanceId));
}
return instance;
}
Example 72
Project: picketbox-quickstarts-master File: DeltaSpikeExceptionHandler.java View source code |
@Override
public void handle() throws FacesException {
Iterator<ExceptionQueuedEvent> it = getUnhandledExceptionQueuedEvents().iterator();
if (it.hasNext()) {
while (it.hasNext()) {
try {
ExceptionQueuedEvent evt = it.next();
Throwable exception = evt.getContext().getException();
ExceptionToCatchEvent etce = new ExceptionToCatchEvent(exception);
beanManager.fireEvent(etce);
} finally {
it.remove();
}
}
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext = facesContext.getExternalContext();
try {
externalContext.redirect(externalContext.getRequestContextPath() + "/error.jsf");
} catch (IOException e) {
}
facesContext.responseComplete();
}
getWrapped().handle();
}
Example 73
Project: portletbridge-master File: WebXMLTest.java View source code |
@Test public void createErrorViews() throws Exception { WebXmlProcessor.facesServlet = new ServletBean(); WebXmlProcessor.facesServlet.getMappings().add("*.jsf"); LinkedHashMap<String, String> pages = new LinkedHashMap<String, String>(); pages.put(IOException.class.getName(), "/foo/bar.jsf"); pages.put(FacesException.class.getName(), "/error/faces.jsf"); pages.put(ServletException.class.getName(), "/foo/bar.jsp"); pages.put("no.such.Exception", "/foo/baz.jsp"); WebXmlProcessor.setErrorPages(pages); WebXmlProcessor webXml = new WebXmlProcessor((PortletContext) null); webXml.createErrorViews(); assertEquals(2, WebXmlProcessor.errorViews.size()); assertEquals("/foo/bar", WebXmlProcessor.errorViews.get(IOException.class)); assertEquals("/error/faces", WebXmlProcessor.errorViews.get(FacesException.class)); }
Example 74
Project: rhq-master File: FaceletRedirectionViewHandler.java View source code |
@Override
protected void handleRenderException(FacesContext context, Exception ex) throws IOException, ELException, FacesException {
try {
if (context.getViewRoot().getViewId().equals("/portal/rhq/common/error.xhtml")) {
/*
* This is to protect from infinite redirects if the error page itself
* has an error; in this case, revert to the default error handling,
* which should provide extra context information to debug the issue
*/
LOG.error("Redirected back to ourselves, there must be a problem with the error.xhtml page", ex);
// normal, ugly error page used to diagnose the issue
super.handleRenderException(context, ex);
// return early, to prevent infinite redirects back to ourselves
return;
}
// let's put this in the server log along with showing the user
LOG.error("Error processing user request", ex);
// squirrel the exception away in the session so it's maintained across the redirect boundary
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext = facesContext.getExternalContext();
Map<String, Object> sessionMap = externalContext.getSessionMap();
sessionMap.put("GLOBAL_RENDER_ERROR", ex);
FacesContextUtility.getResponse().sendRedirect("/portal/rhq/common/error.xhtml");
} catch (IOException ioe) {
LOG.fatal("Could not process redirect to handle application error", ioe);
}
}
Example 75
Project: sakai-cle-master File: SakaiViewHandlerWrapper.java View source code |
public void renderView(FacesContext context, UIViewRoot root) throws IOException, FacesException {
// SAK-20286 start
// Get the request
HttpServletRequest req = (HttpServletRequest) context.getExternalContext().getRequest();
String requestURI = req.getRequestURI();
// Make the attribute name unique to the request
String attrName = "sakai.jsf.tool.URL.loopDetect.viewId-" + requestURI;
// Try to fetch the attribute
Object attribute = req.getAttribute(attrName);
// If the attribute is null, this is the first request for this view
if (attribute == null) {
req.setAttribute(attrName, "true");
} else if (// A looping request is detected.
"true".equals(attribute)) {
HttpServletResponse res = (HttpServletResponse) context.getExternalContext().getResponse();
// Send a 404
res.sendError(404, "File not found: " + requestURI);
}
// SAK-20286 end
getWrapped().renderView(context, root);
}
Example 76
Project: TNTConcept-master File: ApplicationBean.java View source code |
/**
* Inicializa the ApplicationBean.
* <p>
* Carga todas las tablas de referencia
*
* @see BaseBean#init()
*/
protected void init() {
try {
this.logger.debug("Inicializa el ApplicationBean");
/*
List list = this.serviceLocator.getCatalogService().getAllCategories();
for (int i=0; i<list.size(); i++) {
Category c = (Category)list.get(i);
this.categorySelectItems.add(new SelectItem(c.getId(), c.getName(), c.getDescription()));
}*/
this.logger.debug("Application bean está inicializado");
} catch (Exception e) {
String msg = "No puedo inicializar el ApplicationBean ApplicationBean " + e.toString();
this.logger.error(msg);
throw new FacesException(msg);
}
}
Example 77
Project: wildfly-master File: MyFacesLifecycleProvider.java View source code |
public Object newInstance(String className) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NamingException, InvocationTargetException {
final Class<?> clazz = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged().loadClass(className);
if (System.getSecurityManager() == null) {
return clazz.newInstance();
} else {
try {
return AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
public Object run() throws IllegalAccessException, InstantiationException {
return clazz.newInstance();
}
});
} catch (PrivilegedActionException pae) {
Exception e = pae.getException();
if (e instanceof IllegalAccessException) {
throw (IllegalAccessException) e;
} else if (e instanceof InstantiationException) {
throw (InstantiationException) e;
} else {
throw new FacesException(e);
}
}
}
}
Example 78
Project: XPagesExtensionLibrary-master File: UIRedirect.java View source code |
protected void processRedirect(FacesContext context) {
// TODO unused: RedirectRule.isDisableRequestParams (really, go check)
// TODO have a conversation with the Designer team around naming of the property disableRequestParams
// Use cases to get here from Traveler:
// Use case #1 will be translated by NSF application into use case #2
// when particular NSF form will have an XPage associated.
// URL will stay the same #1 format in browser address field.
// 1.
// http://www.acme.com/CCC579050049E718/0E5E7B7972EE57F1802577C2003DF433/4544B55217EB99038025799F0054C209?OpenDocument
// 2.
// http://www.acme.com/teamrm8xl.nsf/topicThread.xsp?action=openDocument&documentId=4544B55217EB99038025799F0054C209
String redirectURL = "";
List<AbstractRedirectRule> rules = getRules();
if (rules != null && rules.size() > 0) {
for (int i = 0; i < rules.size(); i++) {
AbstractRedirectRule redirectRule = rules.get(i);
if (null == redirectRule) {
continue;
}
redirectURL = redirectRule.getRedirectURL(context);
if (!StringUtil.isEmpty(redirectURL)) {
try {
context.getExternalContext().redirect(redirectURL);
} catch (IOException ioe) {
String msg = "Problem applying redirect rule to open {0}";
msg = StringUtil.format(msg, redirectURL);
throw new FacesException(msg, ioe);
}
break;
}
}
}
}
Example 79
Project: com.idega.core-master File: PresentationObjectAttributesMap.java View source code |
private PropertyDescriptor getPropertyDescriptor(String key) {
if (this._propertyDescriptorMap == null) {
BeanInfo beanInfo;
try {
beanInfo = Introspector.getBeanInfo(this._component.getClass());
} catch (IntrospectionException e) {
throw new FacesException(e);
}
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
this._propertyDescriptorMap = new HashMap();
for (int i = 0; i < propertyDescriptors.length; i++) {
PropertyDescriptor propertyDescriptor = propertyDescriptors[i];
if (propertyDescriptor.getReadMethod() != null) {
this._propertyDescriptorMap.put(propertyDescriptor.getName(), propertyDescriptor);
}
}
}
return (PropertyDescriptor) this._propertyDescriptorMap.get(key);
}
Example 80
Project: deltaspike-master File: ClientWindowHelper.java View source code |
/**
* Handles the initial redirect for the LAZY mode, if no windowId is available in the current request URL.
*
* @param facesContext the {@link FacesContext}
* @param newWindowId the new windowId
*/
public static void handleInitialRedirect(FacesContext facesContext, String newWindowId) {
// store the new windowId as context attribute to prevent infinite loops
// #sendRedirect will append the windowId (from ClientWindow#getWindowId again) to the redirectUrl
facesContext.getAttributes().put(INITIAL_REDIRECT_WINDOW_ID, newWindowId);
ExternalContext externalContext = facesContext.getExternalContext();
String url = constructRequestUrl(externalContext);
// remember the initial redirect windowId till the next request - see #729
addRequestWindowIdCookie(facesContext, newWindowId, newWindowId);
try {
externalContext.redirect(url);
} catch (IOException e) {
throw new FacesException("Could not send initial redirect!", e);
}
}
Example 81
Project: encontreaquipecas-master File: CustomExceptionHandler.java View source code |
@Override
public void handle() throws FacesException {
final Iterator<ExceptionQueuedEvent> i = getUnhandledExceptionQueuedEvents().iterator();
while (i.hasNext()) {
ExceptionQueuedEvent event = i.next();
ExceptionQueuedEventContext context = (ExceptionQueuedEventContext) event.getSource();
// get the exception from context
Throwable t = context.getException();
final FacesContext fc = FacesContext.getCurrentInstance();
final Map<String, Object> requestMap = fc.getExternalContext().getRequestMap();
final NavigationHandler nav = fc.getApplication().getNavigationHandler();
//here you do what ever you want with exception
try {
//log error ?
log.log(Level.SEVERE, "Critical Exception!", t);
// Iterate stackTrace to print on error page
StringBuilder stackTraceBuilder = new StringBuilder();
stackTraceBuilder.append(t.getMessage());
stackTraceBuilder.append("\n\n");
if (t.getCause() != null && t.getCause().getStackTrace() != null) {
for (StackTraceElement ex : t.getCause().getStackTrace()) {
stackTraceBuilder.append(ex.toString());
stackTraceBuilder.append("\n");
}
}
//redirect error page
requestMap.put("exceptionMessage", stackTraceBuilder.toString());
nav.handleNavigation(fc, null, "/excecao");
fc.renderResponse();
// remove the comment below if you want to report the error in a jsf error message
//JsfUtil.addErrorMessage(t.getMessage());
} finally {
//remove it from queue
i.remove();
}
}
//parent hanle
getWrapped().handle();
}
Example 82
Project: ivolunteer-master File: SessionBean1.java View source code |
/** * <p> * This method is called when this bean is initially added to session scope. * Typically, this occurs as a result of evaluating a value binding or * method binding expression, which utilizes the managed bean facility to * instantiate this bean and store it into session scope. * </p> * * <p> * You may customize this method to initialize and cache data values or * resources that are required for the lifetime of a particular user * session. * </p> */ @Override public void init() { // Perform initializations inherited from our superclass super.init(); // *Note* - this logic should NOT be modified try { _init(); } catch (Exception e) { log("SessionBean1 Initialization Failure", e); throw e instanceof FacesException ? (FacesException) e : new FacesException(e); } // </editor-fold> // Perform application initialization that must complete // *after* managed components are initialized // TODO - add your own initialization code here }
Example 83
Project: ivolunteer_ori-master File: SessionBean1.java View source code |
/** * <p> * This method is called when this bean is initially added to session scope. * Typically, this occurs as a result of evaluating a value binding or * method binding expression, which utilizes the managed bean facility to * instantiate this bean and store it into session scope. * </p> * * <p> * You may customize this method to initialize and cache data values or * resources that are required for the lifetime of a particular user * session. * </p> */ @Override public void init() { // Perform initializations inherited from our superclass super.init(); // *Note* - this logic should NOT be modified try { _init(); } catch (Exception e) { log("SessionBean1 Initialization Failure", e); throw e instanceof FacesException ? (FacesException) e : new FacesException(e); } // </editor-fold> // Perform application initialization that must complete // *after* managed components are initialized // TODO - add your own initialization code here }
Example 84
Project: JBossAS51-master File: ENCTester.java View source code |
void testENC() throws FacesException { try { // Obtain the environment naming context. Context initCtx = new InitialContext(); Hashtable env = initCtx.getEnvironment(); Iterator keys = env.keySet().iterator(); log.info("InitialContext.env:"); while (keys.hasNext()) { Object key = keys.next(); log.info("Key: " + key + ", value: " + env.get(key)); } Context myEnv = (Context) initCtx.lookup("java:comp/env"); testEjbRefs(initCtx, myEnv); testJdbcDataSource(initCtx, myEnv); testMail(initCtx, myEnv); testJMS(initCtx, myEnv); testURL(initCtx, myEnv); testEnvEntries(initCtx, myEnv); testMessageDestinationRefs(initCtx, myEnv); } catch (NamingException e) { log.debug("Lookup failed", e); throw new FacesException("Lookup failed, ENC tests failed", e); } catch (JMSException e) { log.debug("JMS access failed", e); throw new FacesException("JMS access failed, ENC tests failed", e); } catch (RuntimeException e) { log.debug("Runtime error", e); throw new FacesException("Runtime error, ENC tests failed", e); } }
Example 85
Project: JBossAS_5_1_EDG-master File: ENCTester.java View source code |
void testENC() throws FacesException { try { // Obtain the environment naming context. Context initCtx = new InitialContext(); Hashtable env = initCtx.getEnvironment(); Iterator keys = env.keySet().iterator(); log.info("InitialContext.env:"); while (keys.hasNext()) { Object key = keys.next(); log.info("Key: " + key + ", value: " + env.get(key)); } Context myEnv = (Context) initCtx.lookup("java:comp/env"); testEjbRefs(initCtx, myEnv); testJdbcDataSource(initCtx, myEnv); testMail(initCtx, myEnv); testJMS(initCtx, myEnv); testURL(initCtx, myEnv); testEnvEntries(initCtx, myEnv); testMessageDestinationRefs(initCtx, myEnv); } catch (NamingException e) { log.debug("Lookup failed", e); throw new FacesException("Lookup failed, ENC tests failed", e); } catch (JMSException e) { log.debug("JMS access failed", e); throw new FacesException("JMS access failed, ENC tests failed", e); } catch (RuntimeException e) { log.debug("Runtime error", e); throw new FacesException("Runtime error, ENC tests failed", e); } }
Example 86
Project: jetm-master File: DelegatingEtmLifecycleFactory.java View source code |
@Override
public void render(FacesContext context) throws FacesException {
try {
delegate.render(context);
} finally {
EtmPoint requestPoint = (EtmPoint) context.getAttributes().get(EtmJsfPlugin.ROOT_ETM_POINT);
if (requestPoint != null) {
requestPoint.collect();
context.getAttributes().remove(EtmJsfPlugin.ROOT_ETM_POINT);
}
}
}
Example 87
Project: liferay-faces-util-master File: FactoryExtensionFinder.java View source code |
/** * Returns the thread-safe Singleton instance of the factory extension finder. * * @throws FacesException When the factory extension finder cannot be discovered. */ public static FactoryExtensionFinder getInstance() throws FacesException { // before multiple threads have the opportunity to concurrently access the FactoryExtensionFinder. if (instance == null) { ServiceLoader<FactoryExtensionFinder> serviceLoader = ServiceLoader.load(FactoryExtensionFinder.class); if (serviceLoader != null) { Iterator<FactoryExtensionFinder> iterator = serviceLoader.iterator(); while ((instance == null) && iterator.hasNext()) { instance = iterator.next(); } if (instance == null) { throw new FacesException("Unable locate service for " + FactoryExtensionFinder.class.getName()); } } else { throw new FacesException("Unable to acquire ServiceLoader for " + FactoryExtensionFinder.class.getName()); } } return instance; }
Example 88
Project: platform2-master File: PresentationObjectAttributesMap.java View source code |
private PropertyDescriptor getPropertyDescriptor(String key) {
if (this._propertyDescriptorMap == null) {
BeanInfo beanInfo;
try {
beanInfo = Introspector.getBeanInfo(this._component.getClass());
} catch (IntrospectionException e) {
throw new FacesException(e);
}
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
this._propertyDescriptorMap = new HashMap();
for (int i = 0; i < propertyDescriptors.length; i++) {
PropertyDescriptor propertyDescriptor = propertyDescriptors[i];
if (propertyDescriptor.getReadMethod() != null) {
this._propertyDescriptorMap.put(propertyDescriptor.getName(), propertyDescriptor);
}
}
}
return (PropertyDescriptor) this._propertyDescriptorMap.get(key);
}
Example 89
Project: plato-master File: DefaultExceptionHandler.java View source code |
@Override
public void handle() {
// For each causing exception
for (Iterator<ExceptionQueuedEvent> i = getUnhandledExceptionQueuedEvents().iterator(); i.hasNext(); ) {
// Get causing exception
Throwable exception = i.next().getContext().getException();
i.remove();
FacesContext fc = FacesContext.getCurrentInstance();
ExternalContext externalContext = fc.getExternalContext();
String targetLocation = null;
// Check if we're inside render response and if the response is
// committed.
String message = "";
if (fc.getCurrentPhaseId() != PhaseId.RENDER_RESPONSE) {
message = "An exception occured during processing, redirecting.";
} else if (!externalContext.isResponseCommitted()) {
message = "An exception occured during rendering the response, redirecting.";
// we generate a new response, clean up the old one first
((HttpServletResponse) fc.getExternalContext().getResponse()).reset();
} else {
log.error("An exception occured during rendering the response. Cannot redirect as the response is already commited.");
wrapped.handle();
return;
}
if ((exception instanceof NonexistentConversationException) || (exception instanceof ViewExpiredException)) {
// Redirect session/conversation-timeout error to the start-page
targetLocation = "/index.jsf?sessionExpired=true";
} else {
// we want to know about the cause of this error
log.error(message, exception);
// Redirect all other errors to the bug report-page
// Set the request attributes
HttpServletRequest request = (HttpServletRequest) fc.getExternalContext().getRequest();
final Map<String, Object> sessionMap = fc.getExternalContext().getSessionMap();
sessionMap.put(RequestDispatcher.ERROR_EXCEPTION, exception);
sessionMap.put(RequestDispatcher.ERROR_EXCEPTION_TYPE, exception.getClass());
sessionMap.put(RequestDispatcher.ERROR_MESSAGE, exception.getMessage());
sessionMap.put(RequestDispatcher.ERROR_REQUEST_URI, request.getRequestURI());
sessionMap.put(RequestDispatcher.ERROR_STATUS_CODE, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
targetLocation = "/bugreport.jsf";
}
try {
fc.getExternalContext().redirect(fc.getExternalContext().getRequestContextPath() + targetLocation);
} catch (IOException e) {
throw new FacesException("Error redirecting to error page.", e);
}
// Remove remaining exceptions
while (i.hasNext()) {
i.next();
i.remove();
}
wrapped.handle();
}
}
Example 90
Project: ProjectModel-master File: ActionViewHandler.java View source code |
public void renderView(FacesContext context, UIViewRoot viewRoot) throws IOException, FacesException { String viewId = viewRoot.getViewId(); if (!context.getResponseComplete() && isMapped(viewId)) { NavigationHandler nh = context.getApplication().getNavigationHandler(); ViewHandler vh = context.getApplication().getViewHandler(); String action = (String) context.getExternalContext().getRequestParameterMap().get("action"); String outcome = (String) context.getExternalContext().getRequestParameterMap().get("outcome"); if (action != null) { String method = extractMethodName(action); MethodBinding mb = context.getApplication().createMethodBinding("#{" + action + "}", new Class[0]); outcome = mb.invoke(context, new Object[0]).toString(); nh.handleNavigation(context, method, outcome); if (!context.getResponseComplete() && context.getViewRoot().equals(viewRoot)) { throw new FacesException("No navigation rules from viewId=" + viewId + ", action=" + action + ", outcome=" + outcome + " found."); } } else { nh.handleNavigation(context, null, outcome); if (!context.getResponseComplete() && context.getViewRoot().equals(viewRoot)) { throw new FacesException("No navigation rules from viewId=" + viewId + ", outcome=" + outcome + " found."); } } if (!context.getResponseComplete()) { vh.renderView(context, context.getViewRoot()); } ; } else { viewHandler.renderView(context, viewRoot); } }
Example 91
Project: SocialSDK-master File: JspCompiler.java View source code |
// Generate the JavaScript code that then output the final text
public String compileJsp(String source, String className) throws FacesException {
StringBuilder javaSource = new StringBuilder(2048);
source = generateHeader(javaSource, source, className);
source = extractBody(source);
int slen = source.length();
for (int pos = 0; pos < slen; ) {
int exp = source.indexOf(START_TAG, pos);
int end = exp >= 0 ? exp : slen;
if (end > pos) {
javaSource.append(" emit(out,");
String emit = TextUtil.toJavaString(source.substring(pos, end), true);
javaSource.append(emit);
pos = end;
javaSource.append(");\n");
}
if (exp >= 0) {
int stend = source.indexOf(END_TAG, exp + 2);
if (stend < 0) {
throw new FacesExceptionEx(null, "{0} without a closing {1}", START_TAG, END_TAG);
}
if (source.charAt(exp + 2) == '=') {
String sub = source.substring(exp + 3, stend).trim();
javaSource.append(" emit(out,");
String emit = sub;
javaSource.append(emit);
javaSource.append(");\n");
} else {
String sub = source.substring(exp + 2, stend).trim();
javaSource.append(sub);
if (!sub.endsWith(";")) {
javaSource.append(";");
}
javaSource.append("\n");
}
pos = stend + 2;
}
}
generateFooter(javaSource, className);
return javaSource.toString();
}
Example 92
Project: uBike-master File: CaptchaRenderer.java View source code |
@Override
public void encodeEnd(FacesContext context, UIComponent component) throws IOException {
ResponseWriter writer = context.getResponseWriter();
Captcha captcha = (Captcha) component;
captcha.setRequired(true);
String protocol = captcha.isSecure() ? "https" : "http";
String publicKey = getPublicKey(context, captcha);
if (publicKey == null) {
throw new FacesException("Cannot find public key for catpcha, " + "use com.ubike.PUBLIC_CAPTCHA_KEY context-param to define one");
}
writer.startElement("script", null);
writer.writeAttribute("type", "text/javascript", null);
writer.write("var RecaptchaOptions = {");
writer.write("theme:\"" + captcha.getTheme() + "\"");
writer.write(",lang:\"" + captcha.getLanguage() + "\"");
if (captcha.getTabindex() != 0) {
writer.write(",tabIndex:" + captcha.getTabindex());
}
writer.write("};");
writer.endElement("script");
writer.startElement("script", null);
writer.writeAttribute("type", "text/javascript", null);
writer.writeAttribute("src", protocol + "://www.google.com/recaptcha/api/challenge?k=" + publicKey, null);
writer.endElement("script");
writer.startElement("noscript", null);
writer.startElement("iframe", null);
writer.writeAttribute("src", protocol + "://www.google.com/recaptcha/api/noscript?k=" + publicKey, null);
writer.endElement("iframe");
writer.startElement("textarea", null);
writer.writeAttribute("id", Captcha.CHALLENGE_FIELD, null);
writer.writeAttribute("name", Captcha.CHALLENGE_FIELD, null);
writer.writeAttribute("rows", "3", null);
writer.writeAttribute("columns", "40", null);
writer.endElement("textarea");
writer.startElement("input", null);
writer.writeAttribute("id", Captcha.RESPONSE_FIELD, null);
writer.writeAttribute("name", Captcha.RESPONSE_FIELD, null);
writer.writeAttribute("type", "hidden", null);
writer.writeAttribute("value", "manual_challenge", null);
writer.endElement("input");
writer.endElement("noscript");
}
Example 93
Project: visuwall-master File: BaseRenderer.java View source code |
/** * <p>Return an absolute URI for the current page suitable for use * in a portlet environment. NOTE: Implementation must not require * portlet API classes to be present, so use reflection as needed.</p> * * @param context <code>FacesContext</code> for the current request */ protected String portletUri(FacesContext context) { Object request = context.getExternalContext().getRequest(); try { String scheme = (String) MethodUtils.invokeMethod(request, "getScheme", null); StringBuffer sb = new StringBuffer(scheme); sb.append("://"); sb.append(MethodUtils.invokeMethod(request, "getServerName", null)); Integer port = (Integer) MethodUtils.invokeMethod(request, "getServerPort", null); if ("http".equals(scheme) && (port.intValue() == 80)) { ; } else if ("https".equals(scheme) && (port.intValue() == 443)) { ; } else { sb.append(":" + port); } sb.append(MethodUtils.invokeMethod(request, "getContextPath", null)); sb.append(context.getViewRoot().getViewId()); return (sb.toString()); } catch (InvocationTargetException e) { throw new FacesException(e.getTargetException()); } catch (Exception e) { throw new FacesException(e); } }
Example 94
Project: zeroth-master File: UploadRenderer.java View source code |
/** {@inheritDoc} */
@Override
public void decode(final FacesContext context, final UIComponent component) {
final ExternalContext external = context.getExternalContext();
final HttpServletRequest request = (HttpServletRequest) external.getRequest();
final String clientId = component.getClientId(context);
final FileItem item = (FileItem) request.getAttribute(clientId);
if ((item == null) || StringUtils.isEmpty(item.getName())) {
return;
}
LOG.fine("item:" + item);
final ValueExpression valueExpr = component.getValueExpression("value");
if (valueExpr != null) {
((EditableValueHolder) component).setSubmittedValue(findSubmittedValue(request, item, valueExpr.getType(context.getELContext())));
((EditableValueHolder) component).setValid(true);
}
final Object target = component.getAttributes().get("target");
LOG.fine("target=" + target);
if (target != null) {
File file;
if (target instanceof File) {
file = (File) target;
} else {
final ServletContext servletContext = (ServletContext) external.getContext();
final String itemName = item.getName();
final String dirPath = "WEB-INF/" + target;
LOG.fine("dirPath=" + dirPath);
new File(servletContext.getRealPath(dirPath)).mkdirs();
final String filePath = dirPath + "/" + itemName;
final String realPath = servletContext.getRealPath(filePath);
LOG.fine("realPath=" + realPath);
file = new File(realPath);
}
// UGH 汎用例外クラスをæ?•æ?‰ã?—ã?Ÿã??ã?ªã?„ã?Œcommons-upload仕様ã?Œâ€¦
try {
LOG.fine("item.write");
item.write(file);
} catch (final Exception ex) {
throw new FacesException(ex);
}
}
}
Example 95
Project: openLogOSGi-master File: OpenLogPhaseListener.java View source code |
/** * This is getting VERY complex because of the variety of exceptions and * tracking up the stack trace to find the right class to get as much info * as possible. Extracted into a separate method to make it more readable. * * @param r * requestScope map */ private void processUncaughtException(Map<String, Object> r) { // requestScope.error is not null, we're on the custom error page. Object error = r.get("error"); // Set the agent (page we're on) to the *previous* page OpenLogItem.setThisAgent(false); String msg = ""; if ("com.ibm.xsp.exception.EvaluationExceptionEx".equals(error.getClass().getName())) { // EvaluationExceptionEx, so SSJS error is on a component property. // Hit by ErrorOnLoad.xsp EvaluationExceptionEx ee = (EvaluationExceptionEx) error; InterpretException ie = (InterpretException) ee.getCause(); msg = "Error on " + ee.getErrorComponentId() + " " + ee.getErrorPropertyId() + " property/event, line " + Integer.toString(ie.getErrorLine()) + ":\n\n" + ie.getLocalizedMessage() + "\n\n" + ie.getExpressionText(); OpenLogItem.logErrorEx(ee, msg, null, null); } else if ("javax.faces.FacesException".equals(error.getClass().getName())) { // FacesException, so error is on event or method in EL FacesException fe = (FacesException) error; InterpretException ie = null; EvaluationExceptionEx ee = null; msg = "Error on "; try { // ErrorOnMethod.xsp if (!"javax.faces.el.MethodNotFoundException".equals(fe.getCause().getClass().getName())) { if ("com.ibm.xsp.exception.EvaluationExceptionEx".equals(fe.getCause().getClass().getName())) { // Hit by ErrorOnClick.xsp ee = (EvaluationExceptionEx) fe.getCause(); } else if ("javax.faces.el.PropertyNotFoundException".equals(fe.getCause().getClass().getName())) { // Property not found exception, so error is on a // component property msg = "PropertyNotFoundException Error, cannot locate component:\n\n"; } else if ("com.ibm.xsp.exception.EvaluationExceptionEx".equals(fe.getCause().getCause().getClass().getName())) { // Hit by using e.g. currentDocument.isNewDoc() // i.e. using a Variable that relates to a valid Java // object but a method that doesn't exist ee = (EvaluationExceptionEx) fe.getCause().getCause(); } if (null != ee) { msg = msg + ee.getErrorComponentId() + " " + ee.getErrorPropertyId() + " property/event:\n\n"; if ("com.ibm.jscript.InterpretException".equals(ee.getCause().getClass().getName())) { ie = (InterpretException) ee.getCause(); } } } } catch (Throwable t) { msg = "Unexpected error class: " + fe.getCause().getClass().getName() + "\n Message recorded is: "; } if (null != ie) { msg = msg + Integer.toString(ie.getErrorLine()) + ":\n\n" + ie.getLocalizedMessage() + "\n\n" + ie.getExpressionText(); } else { msg = msg + fe.getCause().getLocalizedMessage(); } OpenLogItem.logErrorEx(fe.getCause(), msg, null, null); } else if ("com.ibm.xsp.FacesExceptionEx".equals(error.getClass().getName())) { // FacesException, so error is on event - doesn't get hit in // examples. Can this still get hit?? FacesExceptionEx fe = (FacesExceptionEx) error; try { if ("lotus.domino.NotesException".equals(fe.getCause().getClass().getName())) { // sometimes the cause is a NotesException NotesException ne = (NotesException) fe.getCause(); msg = msg + "NotesException - " + Integer.toString(ne.id) + " " + ne.text; } else if ("java.io.IOException".equals(error.getClass().getName())) { IOException e = (IOException) error; msg = "Java IO:" + error.toString(); OpenLogItem.logErrorEx(e.getCause(), msg, null, null); } else { EvaluationExceptionEx ee = (EvaluationExceptionEx) fe.getCause(); InterpretException ie = (InterpretException) ee.getCause(); msg = "Error on " + ee.getErrorComponentId() + " " + ee.getErrorPropertyId() + " property/event:\n\n" + Integer.toString(ie.getErrorLine()) + ":\n\n" + ie.getLocalizedMessage() + "\n\n" + ie.getExpressionText(); } } catch (Throwable t) { msg = "Unexpected error class: " + fe.getCause().getClass().getName() + "\n Message recorded is: " + fe.getCause().getLocalizedMessage(); ; } OpenLogItem.logErrorEx(fe.getCause(), msg, null, null); } else if ("javax.faces.el.PropertyNotFoundException".equals(error.getClass().getName())) { // Hit by ErrorOnProperty.xsp // Property not found exception, so error is on a component property PropertyNotFoundException pe = (PropertyNotFoundException) error; msg = "PropertyNotFoundException Error, cannot locate component:\n\n" + pe.getLocalizedMessage(); OpenLogItem.logErrorEx(pe, msg, null, null); } else { try { System.out.println("Error type not found:" + error.getClass().getName()); msg = error.toString(); OpenLogItem.logErrorEx((Throwable) error, msg, null, null); } catch (Throwable t) { t.printStackTrace(); } } }
Example 96
Project: GeoprocessingAppstore-master File: UITableCommandLink.java View source code |
// methods =====================================================================
/* (non-Javadoc)
* @see javax.faces.component.UIComponentBase#encodeBegin(javax.faces.context.FacesContext)
*/
@SuppressWarnings("unchecked")
@Override
public void encodeBegin(FacesContext context) throws IOException {
LOG.fine("Encoding UITableCommandLink " + this);
// Initializing link that will be written out in table
this.indexedLink = this.getIndexedCommandLink(context);
// Getting the form enclosing this link
UIForm enclosingForm = this.uiSupport.findEnclosingFormOf(this);
if (enclosingForm == null) {
throw new FacesException("Component " + this.getId() + "not enclosed in form");
}
// Checking if thisLink.id already exists, if it does, we erase it
UIComponent compExists = this.uiSupport.findComponent(enclosingForm, indexedLink.getId());
if (compExists != null) {
UIForm form = new UIForm();
form.setId(enclosingForm.getId());
form.getChildren().add(this.indexedLink);
} else {
enclosingForm.getChildren().add(indexedLink);
}
// encoding half of thisLink
this.indexedLink.encodeBegin(context);
}
Example 97
Project: GerenciadorEventos-master File: FileUploadRenderer.java View source code |
@Override
public void decode(FacesContext context, UIComponent component) {
FileUpload fileUpload = (FileUpload) component;
if (!fileUpload.isDisabled()) {
ConfigContainer cc = RequestContext.getCurrentInstance().getApplicationContext().getConfig();
String uploader = cc.getUploader();
boolean isAtLeastJSF22 = cc.isAtLeastJSF22();
if (uploader.equals("auto")) {
if (isAtLeastJSF22) {
if (isMultiPartRequest(context))
NativeFileUploadDecoder.decode(context, fileUpload);
} else
CommonsFileUploadDecoder.decode(context, fileUpload);
} else if (uploader.equals("native")) {
if (!isAtLeastJSF22) {
throw new FacesException("native uploader requires at least a JSF 2.2 runtime");
}
NativeFileUploadDecoder.decode(context, fileUpload);
} else if (uploader.equals("commons")) {
CommonsFileUploadDecoder.decode(context, fileUpload);
}
}
}
Example 98
Project: jboss-jsf-api_spec-master File: UIComponentELTag.java View source code |
// ------------------------------------------------------- Protected Methods
/**
* <p>Override properties and attributes of the specified component,
* if the corresponding properties of this tag handler instance were
* explicitly set. This method must be called <strong>ONLY</strong>
* if the specified {@link UIComponent} was in fact created during
* the execution of this tag handler instance, and this call will occur
* <strong>BEFORE</strong> the {@link UIComponent} is added to
* the view.</p>
*
* <p>Tag subclasses that want to support additional set properties
* must ensure that the base class <code>setProperties()</code>
* method is still called. A typical implementation that supports
* extra properties <code>foo</code> and <code>bar</code> would look
* something like this:</p>
* <pre>
* protected void setProperties(UIComponent component) {
* super.setProperties(component);
* if (foo != null) {
* component.setAttribute("foo", foo);
* }
* if (bar != null) {
* component.setAttribute("bar", bar);
* }
* }
* </pre>
*
* <p>The default implementation overrides the following properties:</p>
* <ul>
* <li><code>rendered</code> - Set if a value for the
* <code>rendered</code> property is specified for
* this tag handler instance.</li>
* <li><code>rendererType</code> - Set if the <code>getRendererType()</code>
* method returns a non-null value.</li>
* </ul>
*
* @param component {@link UIComponent} whose properties are to be
* overridden
*/
protected void setProperties(UIComponent component) {
// so it does not need to be set here
if (rendered != null) {
if (rendered.isLiteralText()) {
try {
component.setRendered(Boolean.valueOf(rendered.getExpressionString()).booleanValue());
} catch (ELException e) {
throw new FacesException(e);
}
} else {
component.setValueExpression("rendered", rendered);
}
}
if (getRendererType() != null) {
component.setRendererType(getRendererType());
}
}
Example 99
Project: jsf-test-master File: StubApplication.java View source code |
@Override
public UIComponent createComponent(String name) throws FacesException {
// Best guess component creation with a dummy component if it can't be found
if (name.startsWith("org.jboss.seam.mail.ui") || name.startsWith("org.jboss.seam.excel.ui")) {
try {
return (UIComponent) Class.forName(name).newInstance();
} catch (Exception e) {
throw new UnsupportedOperationException("Unable to create component " + name);
}
} else {
// Oh well, can't simply create the component so put a dummy one in its place
return new UIOutput();
}
}
Example 100
Project: rewrite-master File: ParameterValidator.java View source code |
private void validatePathParams(final FacesContext context, final URL url, final UrlMapping mapping) {
List<PathParameter> params = mapping.getPatternParser().parse(url);
PathParameter currentParameter = new PathParameter();
PathValidator currentPathValidator = new PathValidator();
String currentValidatorId = "";
try {
for (PathParameter param : params) {
currentParameter = param;
List<PathValidator> validators = mapping.getValidatorsForPathParam(param);
if (validators != null && validators.size() > 0) {
String value = param.getValue();
Object coerced = elUtils.coerceToType(context, param.getExpression().getELExpression(), value);
for (PathValidator pv : validators) {
currentPathValidator = pv;
for (String id : pv.getValidatorIdList()) {
currentValidatorId = id;
Validator validator = context.getApplication().createValidator(id);
validator.validate(context, new NullComponent(), coerced);
}
if (pv.getValidatorExpression() != null) {
elUtils.invokeMethod(context, pv.getValidatorExpression().getELExpression(), new Class<?>[] { FacesContext.class, UIComponent.class, Object.class }, new Object[] { context, new NullComponent(), coerced });
}
}
}
}
} catch (ELException e) {
FacesMessage message = new FacesMessage("Could not coerce value [" + currentParameter.getValue() + "] on mappingId [" + mapping.getId() + "] to type in location [" + currentParameter.getExpression() + "]");
handleValidationFailure(context, message, currentPathValidator.getOnError());
} catch (ValidatorException e) {
handleValidationFailure(context, e.getFacesMessage(), currentPathValidator.getOnError());
} catch (FacesException e) {
FacesMessage message = new FacesMessage("Error occurred invoking validator with id [" + currentValidatorId + "] on mappingId [" + mapping.getId() + "] parameter [" + currentParameter.getExpression() + "] at position [" + currentParameter.getPosition() + "]");
handleValidationFailure(context, message, currentPathValidator.getOnError());
}
}
Example 101
Project: weblets111_temp-master File: WebletsPhaseListener.java View source code |
protected void doBeforePhase(PhaseEvent event) { FacesContext context = FacesContext.getCurrentInstance(); ExternalContext external = context.getExternalContext(); // test stuff remove me once verified WebletUtilsImpl utils = new WebletUtilsImpl(); WebletRequest req = null; /* * req = utils.getRequestFromPath(external.getRequest(), "/weblets-demo/faces/weblets/demo$1.0/welcome.js"); * * ServletContext ctx = (ServletContext) external.getContext(); String mime = ctx.getMimeType("/faces/weblets/demo$1.0/welcome.js"); * * InputStream strm = utils.getResourceAsStream(req, mime); BufferedReader istrm = new BufferedReader(new InputStreamReader(strm)); try { String line = * ""; while ((line = istrm.readLine() ) != null) { System.out.println(line); } istrm.close(); * * } catch (IOException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } * * * req = utils.getRequestFromPath(external.getRequest(), "/faces/weblets/demo$1.0/welcome.js"); utils.getResourceAsStream(req, mime); * * req = utils.getRequestFromPath(external.getRequest(), "http://localhost:8080/weblets-demo/faces/weblets/demo$1.0/welcome.js"); * utils.getResourceAsStream(req, mime); * * req = utils.getRequestFromPath(external.getRequest(), "/xxx/aa/demo$1.0/welcome.js"); utils.getResourceAsStream(req, mime); * * * req = utils.getRequestFromPath(external.getRequest(), "/xxx/aa/demo$1.0/booga.js"); Object strobj = utils.getResourceAsStream(req, mime); */ WebletContainerImpl container = (WebletContainerImpl) WebletContainer.getInstance(); String pathInfo = external.getRequestServletPath(); if (pathInfo != null && external.getRequestPathInfo() != null) pathInfo += external.getRequestPathInfo(); if (pathInfo == null && event.getPhaseId() == PhaseId.RESTORE_VIEW) { // we are in a portlet environment here, since we do not get an external path info // we skip this phase and renter after the restore view event.getFacesContext().getExternalContext().getRequestMap().put(WEBLETS_PHASE_LISTENER_ENTERED, Boolean.FALSE); return; } // in some portlet environments if (pathInfo == null) pathInfo = context.getViewRoot().getViewId(); Matcher matcher = null; try { matcher = container.getPattern().matcher(pathInfo); } catch (NullPointerException ex) { Log log = LogFactory.getLog(this.getClass()); log.error("An error has occurred no pattern or matcher has been detected, this is probably a sign that the weblets context listener has not been started. please add following lines to your web.xml \n" + " <listener>\n" + " <listener-class>net.java.dev.weblets.WebletsContextListener</listener-class>\n" + " </listener>"); log.error("Details of the original Error:" + ex.toString()); return; } if (matcher.matches()) { Map requestHeaders = external.getRequestHeaderMap(); String contextPath = external.getRequestContextPath(); String requestURI = matcher.group(1); String ifModifiedHeader = (String) requestHeaders.get("If-Modified-Since"); long ifModifiedSince = -1L; if (ifModifiedHeader != null) { try { DateFormat rfc1123 = new HttpDateFormat(); Date parsed = rfc1123.parse(ifModifiedHeader); ifModifiedSince = parsed.getTime(); } catch (ParseException e) { throw new FacesException(e); } } try { String[] parsed = container.parseWebletRequest(contextPath, requestURI, ifModifiedSince); if (parsed != null) { ServletContext servletContext = (ServletContext) external.getContext(); ServletRequest httpRequest = (ServletRequest) external.getRequest(); ServletResponse httpResponse = (ServletResponse) external.getResponse(); String webletName = parsed[0]; String webletPath = parsed[1]; String webletPathInfo = parsed[2]; WebletRequest webRequest = new WebletRequestImpl(webletName, webletPath, contextPath, webletPathInfo, ifModifiedSince, httpRequest); String contentName = webRequest.getPathInfo(); String contentTypeDefault = servletContext.getMimeType(contentName); WebletResponse webResponse = new WebletResponseImpl(contentTypeDefault, httpResponse); container.service(webRequest, webResponse); context.responseComplete(); } } catch (IOException e) { throw new FacesException(e); } } }