Example usage for java.lang Throwable getLocalizedMessage

List of usage examples for java.lang Throwable getLocalizedMessage

Introduction

In this page you can find the example usage for java.lang Throwable getLocalizedMessage.

Prototype

public String getLocalizedMessage() 

Source Link

Document

Creates a localized description of this throwable.

Usage

From source file:org.pentaho.platform.engine.core.system.PentahoSystem.java

public static void sessionStartup(final IPentahoSession session, IParameterProvider sessionParameters) {

    List<ISessionStartupAction> sessionStartupActions = PentahoSystem
            .getSessionStartupActionsForType(session.getClass().getName());
    if (sessionStartupActions == null) {
        // nothing to do...
        return;//  w ww  . jav a 2 s.co  m
    }

    if (!session.isAuthenticated()) {
        return;
    }

    if (debug) {
        Logger.debug(PentahoSystem.class, "Process session startup actions"); //$NON-NLS-1$
    }
    // TODO this needs more validation
    if (sessionStartupActions != null) {
        for (ISessionStartupAction sessionStartupAction : sessionStartupActions) {
            // parse the actionStr out to identify an action
            // now execute the action...

            SimpleOutputHandler outputHandler = null;

            String instanceId = null;

            ISolutionEngine solutionEngine = PentahoSystem.get(ISolutionEngine.class, session);
            solutionEngine.setLoggingLevel(PentahoSystem.loggingLevel);
            solutionEngine.init(session);

            String baseUrl = ""; //$NON-NLS-1$
            HashMap parameterProviderMap = new HashMap();
            if (sessionParameters == null) {
                sessionParameters = new PentahoSessionParameterProvider(session);
            }

            parameterProviderMap.put(SCOPE_SESSION, sessionParameters);

            IPentahoUrlFactory urlFactory = new SimpleUrlFactory(baseUrl);

            ArrayList messages = new ArrayList();

            IRuntimeContext context = null;
            try {
                context = solutionEngine.execute(sessionStartupAction.getActionPath(),
                        "Session startup actions", false, true, instanceId, false, parameterProviderMap,
                        outputHandler, null, urlFactory, messages); //$NON-NLS-1$

                // if context is null, then we cannot check the status
                if (null == context) {
                    return;
                }

                if (context.getStatus() == IRuntimeContext.RUNTIME_STATUS_SUCCESS) {
                    // now grab any outputs
                    Iterator outputNameIterator = context.getOutputNames().iterator();
                    while (outputNameIterator.hasNext()) {

                        String attributeName = (String) outputNameIterator.next();
                        IActionParameter output = context.getOutputParameter(attributeName);

                        Object data = output.getValue();
                        if (data != null) {
                            session.removeAttribute(attributeName);
                            session.setAttribute(attributeName, data);
                        }
                    }
                }
            } catch (Throwable th) {
                Logger.warn(PentahoSystem.class.getName(), Messages.getInstance().getString(
                        "PentahoSystem.WARN_UNABLE_TO_EXECUTE_SESSION_ACTION", th.getLocalizedMessage()), th); //$NON-NLS-1$
            } finally {
                if (context != null) {
                    context.dispose();
                }
            }
        }
    }
}

From source file:org.pentaho.platform.web.http.api.resources.UserRoleDaoResource.java

/**
 * Associates selected role(s) to a user
 *
 * @param tenantPath (tenant path where the user exist, null of empty string assumes default tenant)
 * @param userName   (username)/*ww w .  java2s. co  m*/
 * @param roleNames  (tab (\t) separated list of role names)
 * @return
 */
@PUT
@Path("/assignRoleToUser")
@Consumes({ WILDCARD })
@Facet(name = "Unsupported")
public Response assignRoleToUser(@QueryParam("tenant") String tenantPath,
        @QueryParam("userName") String userName, @QueryParam("roleNames") String roleNames) {
    if (canAdminister()) {
        IUserRoleDao roleDao = PentahoSystem.get(IUserRoleDao.class, "userRoleDaoProxy",
                PentahoSessionHolder.getSession());
        StringTokenizer tokenizer = new StringTokenizer(roleNames, "\t");
        Set<String> assignedRoles = new HashSet<String>();
        for (IPentahoRole pentahoRole : roleDao.getUserRoles(getTenant(tenantPath), userName)) {
            assignedRoles.add(pentahoRole.getName());
        }
        while (tokenizer.hasMoreTokens()) {
            assignedRoles.add(tokenizer.nextToken());
        }
        try {
            roleDao.setUserRoles(getTenant(tenantPath), userName, assignedRoles.toArray(new String[0]));
        } catch (Throwable th) {
            return processErrorResponse(th.getLocalizedMessage());
        }
        return Response.ok().build();
    } else {
        return Response.status(UNAUTHORIZED).build();
    }
}

From source file:org.pentaho.platform.web.http.api.resources.UserRoleDaoResource.java

/**
 * Remove selected roles(s) from a selected user
 *
 * @param tenantPath (tenant path where the user exist, null of empty string assumes default tenant)
 * @param userName   (username)//  ww w  .  j  a  va2 s.  c o  m
 * @param roleNames  (tab (\t) separated list of role names)
 * @return
 */
@PUT
@Path("/removeRoleFromUser")
@Consumes({ WILDCARD })
@Facet(name = "Unsupported")
public Response removeRoleFromUser(@QueryParam("tenant") String tenantPath,
        @QueryParam("userName") String userName, @QueryParam("roleNames") String roleNames) {
    if (canAdminister()) {
        try {
            IUserRoleDao roleDao = PentahoSystem.get(IUserRoleDao.class, "userRoleDaoProxy",
                    PentahoSessionHolder.getSession());
            StringTokenizer tokenizer = new StringTokenizer(roleNames, "\t");
            Set<String> assignedRoles = new HashSet<String>();
            for (IPentahoRole pentahoRole : roleDao.getUserRoles(getTenant(tenantPath), userName)) {
                assignedRoles.add(pentahoRole.getName());
            }
            while (tokenizer.hasMoreTokens()) {
                assignedRoles.remove(tokenizer.nextToken());
            }
            roleDao.setUserRoles(getTenant(tenantPath), userName, assignedRoles.toArray(new String[0]));
            return Response.ok().build();
        } catch (Throwable th) {
            return processErrorResponse(th.getLocalizedMessage());
        }
    } else {
        return Response.status(UNAUTHORIZED).build();
    }
}

From source file:org.pentaho.platform.web.http.api.resources.UserRoleDaoResource.java

/**
 * Associate list of users to the selected role
 *
 * @param tenantPath (tenant path where the user exist, null of empty string assumes default tenant)
 * @param userNames  (list of tab (\t) separated user names
 * @param roleName   (role name)/*w ww .j av  a 2  s. com*/
 * @return
 */
@PUT
@Path("/assignUserToRole")
@Consumes({ WILDCARD })
@Facet(name = "Unsupported")
public Response assignUserToRole(@QueryParam("tenant") String tenantPath,
        @QueryParam("userNames") String userNames, @QueryParam("roleName") String roleName) {
    if (canAdminister()) {
        IUserRoleDao roleDao = PentahoSystem.get(IUserRoleDao.class, "userRoleDaoProxy",
                PentahoSessionHolder.getSession());
        StringTokenizer tokenizer = new StringTokenizer(userNames, "\t");
        Set<String> assignedUserNames = new HashSet<String>();
        for (IPentahoUser pentahoUser : roleDao.getRoleMembers(getTenant(tenantPath), roleName)) {
            assignedUserNames.add(pentahoUser.getUsername());
        }
        while (tokenizer.hasMoreTokens()) {
            assignedUserNames.add(tokenizer.nextToken());
        }
        try {
            roleDao.setRoleMembers(getTenant(tenantPath), roleName, assignedUserNames.toArray(new String[0]));
            return Response.ok().build();
        } catch (Throwable th) {
            return processErrorResponse(th.getLocalizedMessage());
        }
    } else {
        return Response.status(UNAUTHORIZED).build();
    }
}

From source file:org.pentaho.platform.web.http.api.resources.UserRoleDaoResource.java

/**
 * Remove user(s) from a particular role
 *
 * @param tenantPath (tenant path where the user exist, null of empty string assumes default tenant)
 * @param userNames  (list of tab (\t) separated user names
 * @param roleName   (role name)//from  ww  w. ja va2s.  c o  m
 * @return
 */
@PUT
@Path("/removeUserFromRole")
@Consumes({ WILDCARD })
@Facet(name = "Unsupported")
public Response removeUserFromRole(@QueryParam("tenant") String tenantPath,
        @QueryParam("userNames") String userNames, @QueryParam("roleName") String roleName) {
    if (canAdminister()) {
        try {
            IUserRoleDao roleDao = PentahoSystem.get(IUserRoleDao.class, "userRoleDaoProxy",
                    PentahoSessionHolder.getSession());
            StringTokenizer tokenizer = new StringTokenizer(userNames, "\t");
            Set<String> assignedUserNames = new HashSet<String>();
            for (IPentahoUser pentahoUser : roleDao.getRoleMembers(getTenant(tenantPath), roleName)) {
                assignedUserNames.add(pentahoUser.getUsername());
            }
            while (tokenizer.hasMoreTokens()) {
                assignedUserNames.remove(tokenizer.nextToken());
            }
            roleDao.setRoleMembers(getTenant(tenantPath), roleName, assignedUserNames.toArray(new String[0]));
            return Response.ok().build();
        } catch (Throwable th) {
            return processErrorResponse(th.getLocalizedMessage());
        }
    } else {
        return Response.status(UNAUTHORIZED).build();
    }
}

From source file:org.apache.hadoop.ha.HealthMonitor.java

private void doHealthChecks() throws InterruptedException {
    while (shouldRun) {
        HAServiceStatus status = null;//from   ww  w  .jav a2s. com
        boolean healthy = false;
        try {
            status = proxy.getServiceStatus();
            proxy.monitorHealth();
            healthy = true;
        } catch (Throwable t) {
            if (isHealthCheckFailedException(t)) {
                LOG.warn("Service health check failed for " + targetToMonitor + ": " + t.getMessage());
                enterState(State.SERVICE_UNHEALTHY);
            } else {
                LOG.warn("Transport-level exception trying to monitor health of " + targetToMonitor + ": "
                        + t.getCause() + " " + t.getLocalizedMessage());
                RPC.stopProxy(proxy);
                proxy = null;
                enterState(State.SERVICE_NOT_RESPONDING);
                Thread.sleep(sleepAfterDisconnectMillis);
                return;
            }
        }

        if (status != null) {
            setLastServiceStatus(status);
        }
        if (healthy) {
            enterState(State.SERVICE_HEALTHY);
        }

        Thread.sleep(checkIntervalMillis);
    }
}

From source file:com.gelakinetic.mtgfam.fragments.TradeFragment.java

@Override
protected void onCardPriceLookupFailure(MtgCard data, Throwable exception) {
    data.mMessage = exception.getLocalizedMessage();
    data.mPriceInfo = null;//  www. ja  v a 2 s  . co m
}

From source file:com.metasys.cmis.stages.Stage.java

public void execute(Tag root) throws OperationFailedException {
    List<Tag> children = root.getChildren();

    for (Tag c : children) {
        if (!methodMappings.containsKey(c.getName())) {
            logger.error("Invalid action specified: " + c.getName());
            continue;
        }// w  w  w  .ja  v a 2 s  .  c  o m
        boolean failed = false;
        String errorMessage = "";
        try {
            MethodUtils.invokeMethod(this, methodMappings.get(c.getName()), c);
        } catch (NoSuchMethodException noMethod) {
            logger.error("Error:", noMethod);
            failed = true;
        } catch (IllegalAccessException illegalMethod) {
            logger.error("Error:", illegalMethod);
            failed = true;
        } catch (InvocationTargetException invocationMethod) {
            logger.error("Error:", invocationMethod);
            Throwable cause = invocationMethod.getCause();
            if (cause != null && cause instanceof CmisBaseException) {
                errorMessage = ExceptionParser.parseException(connector,
                        ((CmisBaseException) cause).getErrorContent());
                if (errorMessage == null)
                    errorMessage = cause.getLocalizedMessage();
            } else
                errorMessage = cause.getMessage();
            failed = true;
        }

        String exceptionMessage = "Failed during operation '" + c.getName() + "' with error: " + errorMessage;
        if (CMISInBatch.stopOnFail && failed)
            throw new OperationFailedException(exceptionMessage);
        else if (failed)
            logger.error(exceptionMessage);
    }
}

From source file:connectivity.ClarolineService.java

/**
 * Gets the last updates.//from w w w  .  ja va 2  s  .  c  om
 * 
 * @param handler
 *            the handler to execute if the request is successful
 */
public void getUpdates(final AsyncHttpResponseHandler handler) {
    RequestParams p = ClarolineClient.getRequestParams(SupportedModules.USER, SupportedMethods.getUpdates);
    mClient.serviceQuery(p, new JsonHttpResponseHandler() {

        @Override
        public void onFailure(final Throwable e, final String array) {
            Log.e("ClarolineClient", "FAILURE ! :" + e.getLocalizedMessage());
        }

        @Override
        public void onFinish() {
            handler.onFinish();
        }

        @Override
        public void onSuccess(final JSONArray response) {
            handler.onSuccess(response.toString());
        }

        @SuppressWarnings("unchecked")
        @Override
        public void onSuccess(final JSONObject object) {

            Iterator<String> iterOnCours = object.keys();
            while (iterOnCours.hasNext()) {
                final String syscode = iterOnCours.next();
                final Cours upCours = new Select().from(Cours.class).where("Syscode = ?", syscode)
                        .executeSingle();

                if (upCours == null) {
                    getCourseList(new AsyncHttpResponseHandler() {
                        @Override
                        public void onSuccess(final String content) {
                            Cours cours = new Select().from(Cours.class).where("Syscode = ?", syscode)
                                    .executeSingle();

                            if (cours != null) {
                                updateCompleteCourse(cours, null, new AsyncHttpResponseHandler());
                            }
                        }
                    });
                    continue;
                } else {
                    try {
                        JSONObject jsonCours = object.getJSONObject(syscode);
                        Iterator<String> iterOnMod = jsonCours.keys();
                        while (iterOnMod.hasNext()) {
                            final String modKey = iterOnMod.next();
                            ResourceList upList = new Select().from(ResourceList.class)
                                    .where("Cours = ? AND label = ?", upCours, modKey).executeSingle();

                            if (upList == null) {
                                getToolListForCours(upCours, new AsyncHttpResponseHandler() {
                                    @Override
                                    public void onSuccess(final String content) {
                                        ResourceList list = new Select().from(ResourceList.class)
                                                .where("Cours = ? AND label = ?", upCours, modKey)
                                                .executeSingle();
                                        if (list != null) {
                                            getResourcesForList(list, new AsyncHttpResponseHandler());
                                        }
                                    }
                                });
                                continue;
                            } else {
                                try {
                                    JSONObject jsonRes = jsonCours.getJSONObject(modKey);
                                    Iterator<String> iterOnKeys = jsonRes.keys();
                                    while (iterOnKeys.hasNext()) {
                                        String resourceString = iterOnKeys.next();
                                        ModelBase upRes = new Select()
                                                .from(SupportedModules.getTypeForModule(modKey))
                                                .where("List = ?", upList).executeSingle();
                                        if (upRes == null) {
                                            getResourcesForList(upList, new AsyncHttpResponseHandler());
                                        } else {
                                            DateTime date = DateTime.parse(
                                                    jsonRes.optString(resourceString, ""),
                                                    DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss"));
                                            upRes.setDate(date);
                                            upRes.setNotifiedDate(date);
                                        }
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }

                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            handler.onSuccess(object.toString());
        }
    });
}

From source file:com.microsoft.tfs.client.common.ui.tasks.ConnectTask.java

/**
 * {@inheritDoc}/*from  w ww  .j av a  2  s  .  com*/
 */
@Override
public IStatus run() {
    /* Try to get some credentials */
    if (credentials == null) {
        final CachedCredentials cachedCredentials = EclipseCredentialsManagerFactory
                .getCredentialsManager(DefaultPersistenceStoreProvider.INSTANCE).getCredentials(serverURI);

        // try to use DefaultNTCredentials when no credentials acquired
        credentials = cachedCredentials != null ? cachedCredentials.toCredentials()
                : new DefaultNTCredentials();
    }

    /*
     * We may have stored credentials that are not complete - if so, prompt.
     */
    if (credentials == null || CredentialsUtils.needsPassword(credentials)) {
        final CredentialsDialog credentialsDialog = new CredentialsDialog(getShell(), serverURI);
        credentialsDialog.setCredentials(credentials);
        credentialsDialog.setAllowSavePassword(CredentialsManagerFactory
                .getCredentialsManager(DefaultPersistenceStoreProvider.INSTANCE).canWrite());

        if (UIHelpers.openOnUIThread(credentialsDialog) != IDialogConstants.OK_ID) {
            return Status.CANCEL_STATUS;
        }

        credentials = credentialsDialog.getCredentials();
    }

    IStatus status = Status.CANCEL_STATUS;

    while (connection == null) {
        final ConnectCommand connectCommand = getConnectCommand(serverURI, credentials);

        status = getCommandExecutor().execute(new ThreadedCancellableCommand(connectCommand));

        connectCommandFinished(connectCommand);

        if (status.isOK()) {
            connection = connectCommand.getConnection();
            break;
        } else if (status.getSeverity() != IStatus.CANCEL) {
            /* See if we can get an Exception out of the error. */
            final Throwable exception = (status instanceof TeamExplorerStatus)
                    ? ((TeamExplorerStatus) status).getTeamExplorerException()
                    : null;

            /* On unauthorized exceptions, prompt for the password again */
            if (exception != null && (exception instanceof TFSUnauthorizedException)) {
                final CredentialsDialog credentialsDialog = new CredentialsDialog(getShell(), serverURI);
                credentialsDialog.setErrorMessage(exception.getLocalizedMessage());
                credentialsDialog.setCredentials(credentials);
                credentialsDialog.setAllowSavePassword(CredentialsManagerFactory
                        .getCredentialsManager(DefaultPersistenceStoreProvider.INSTANCE).canWrite());

                if (UIHelpers.openOnUIThread(credentialsDialog) == IDialogConstants.OK_ID) {
                    credentials = credentialsDialog.getCredentials();
                    continue;
                }
            } else if (exception != null && exception instanceof TransportRequestHandlerCanceledException) {
                // User canceled; ignore exception
            } else if (showErrorDialog) {
                if (exception != null) {
                    log.warn("Unexpected connection exception", exception); //$NON-NLS-1$
                }

                final IStatus errorStatus = status;

                UIHelpers.runOnUIThread(false, new Runnable() {
                    @Override
                    public void run() {
                        ErrorDialog.openError(getShell(),
                                Messages.getString("TeamProjectSelectControl.ConnectionFailedDialogTitle"), //$NON-NLS-1$
                                null, errorStatus);
                    }
                });
            }
        }

        break;
    }

    return status;
}