Search in sources :

Example 1 with ExitCode

use of org.glassfish.api.ActionReport.ExitCode in project Payara by payara.

the class TemplateRestResource method doDelete.

protected ExitCode doDelete(HashMap<String, String> data) {
    if (data == null) {
        data = new HashMap<String, String>();
    }
    if (entity == null) {
        // wrong resource
        // return Response.status(404).entity(ResourceUtil.getActionReportResult(ActionReport.ExitCode.FAILURE, errorMessage, requestHeaders, uriInfo)).build();
        throwError(Status.NOT_FOUND, localStrings.getLocalString("rest.resource.erromessage.noentity", "Resource not found."));
    }
    if (getDeleteCommand() == null) {
        String message = localStrings.getLocalString("rest.resource.delete.forbidden", "DELETE on \"{0}\" is forbidden.", new Object[] { uriInfo.getAbsolutePath() });
        throwError(Status.FORBIDDEN, message);
    }
    if (getDeleteCommand().equals("GENERIC-DELETE")) {
        try {
            ConfigBean p = (ConfigBean) parent;
            if (parent == null) {
                p = (ConfigBean) entity.parent();
            }
            ConfigSupport.deleteChild(p, (ConfigBean) entity);
            return ExitCode.SUCCESS;
        } catch (TransactionFailure ex) {
            throw new WebApplicationException(ex, Response.Status.INTERNAL_SERVER_ERROR);
        }
    }
    // do the delete via the command:
    if (data.containsKey("error")) {
        throwError(Status.BAD_REQUEST, localStrings.getLocalString("rest.request.parsing.error", "Unable to parse the input entity. Please check the syntax."));
    }
    ResourceUtil.addQueryString(uriInfo.getQueryParameters(), data);
    ResourceUtil.purgeEmptyEntries(data);
    ResourceUtil.adjustParameters(data);
    if (data.get("DEFAULT") == null) {
        addDefaultParameter(data);
    } else {
        String resourceName = getResourceName(uriInfo.getAbsolutePath().getPath(), "/");
        if (!data.get("DEFAULT").equals(resourceName)) {
            throwError(Status.FORBIDDEN, localStrings.getLocalString("rest.resource.not.deleted", "Resource not deleted. Value of \"name\" should be the name of this resource."));
        }
    }
    RestActionReporter actionReport = runCommand(getDeleteCommand(), data);
    if (actionReport != null) {
        ActionReport.ExitCode exitCode = actionReport.getActionExitCode();
        if (exitCode != ActionReport.ExitCode.FAILURE) {
            return exitCode;
        }
        throwError(Status.BAD_REQUEST, actionReport.getMessage());
    }
    throw new WebApplicationException(handleError(Status.BAD_REQUEST, localStrings.getLocalString("rest.resource.delete.forbidden", "DELETE on \"{0}\" is forbidden.", new Object[] { uriInfo.getAbsolutePath() })));
}
Also used : TransactionFailure(org.jvnet.hk2.config.TransactionFailure) WebApplicationException(javax.ws.rs.WebApplicationException) RestActionReporter(org.glassfish.admin.rest.utils.xml.RestActionReporter) ConfigBean(org.jvnet.hk2.config.ConfigBean) ExitCode(org.glassfish.api.ActionReport.ExitCode) ActionReport(org.glassfish.api.ActionReport)

Example 2 with ExitCode

use of org.glassfish.api.ActionReport.ExitCode in project Payara by payara.

the class RestUtil method parseResponse.

public static Map<String, Object> parseResponse(RestResponse response, HandlerContext handlerCtx, String endpoint, Object attrs, boolean quiet, boolean throwException) {
    // Parse the response
    String message = "";
    ExitCode exitCode = ExitCode.FAILURE;
    Object maskedAttr = attrs;
    if ((attrs != null) && (attrs instanceof Map)) {
        maskedAttr = maskOffPassword((Map<String, Object>) attrs);
    }
    if (response != null) {
        try {
            // int status = response.getResponseCode();
            Map<String, Object> responseMap = response.getResponse();
            if (responseMap.get("data") != null) {
                String exitCodeStr = (String) ((Map<String, Object>) responseMap.get("data")).get("exit_code");
                exitCode = (exitCodeStr != null) ? ExitCode.valueOf(exitCodeStr) : ExitCode.SUCCESS;
            }
            // Get the message for both WARNING and FAILURE exit_code
            if (exitCode != ExitCode.SUCCESS) {
                Map<String, Object> dataMap = (Map<String, Object>) responseMap.get("data");
                if (dataMap != null) {
                    message = getMessage(dataMap);
                    List<Map<String, Object>> subReports = (List<Map<String, Object>>) dataMap.get("subReports");
                    if (subReports != null) {
                        StringBuilder sb = new StringBuilder("");
                        for (Map<String, Object> oneSubReport : subReports) {
                            sb.append(" ").append(getMessage(oneSubReport));
                        }
                        message = message + sb.toString();
                    }
                } else {
                    Object msgs = responseMap.get("message");
                    if (msgs == null) {
                        // According to security guideline, we shouldn't expose the endpoint to user for the error.
                        // message =  "REST Request '"  + endpoint + "' failed with response code '" + status + "'.";
                        message = "";
                    } else if (msgs instanceof List) {
                        StringBuilder builder = new StringBuilder("");
                        for (Object obj : ((List<Object>) msgs)) {
                            if ((obj instanceof Map) && ((Map<String, Object>) obj).containsKey("message")) {
                                obj = ((Map<String, Object>) obj).get("message");
                            }
                            builder.append(obj.toString());
                        }
                        message = builder.toString();
                    } else if (msgs instanceof Map) {
                        message = ((Map<String, Object>) msgs).get("message").toString();
                    } else {
                        throw new RuntimeException("Unexpected message type.");
                    }
                }
            }
            switch(exitCode) {
                case FAILURE:
                    {
                        // If this is called from jsf, stop processing/show error.
                        if (throwException) {
                            if (handlerCtx != null) {
                                GuiUtil.handleError(handlerCtx, message);
                                if (!quiet) {
                                    Logger logger = GuiUtil.getLogger();
                                    logger.severe(GuiUtil.getCommonMessage("LOG_REQUEST_RESULT", new Object[] { exitCode, endpoint, maskedAttr }));
                                    if (logger.isLoggable(Level.FINEST)) {
                                        logger.finest("response.getResponseBody(): " + response.getResponseBody());
                                    }
                                }
                                return new HashMap();
                            } else {
                                // If handlerCtx is not passed in, it means the caller (java handler) wants to handle this exception itself.
                                throw new RuntimeException(message);
                            }
                        } else {
                            // Issue Number :13312 handling the case when throwException is false.
                            if (!quiet) {
                                Logger logger = GuiUtil.getLogger();
                                logger.severe(GuiUtil.getCommonMessage("LOG_REQUEST_RESULT", new Object[] { exitCode, endpoint, maskedAttr }));
                                if (logger.isLoggable(Level.FINEST)) {
                                    logger.finest("response.getResponseBody(): " + response.getResponseBody());
                                }
                            }
                            return responseMap;
                        }
                    }
                case WARNING:
                    {
                        GuiUtil.prepareAlert("warning", GuiUtil.getCommonMessage("msg.command.warning"), message);
                        GuiUtil.getLogger().warning(GuiUtil.getCommonMessage("LOG_REQUEST_RESULT", new Object[] { exitCode, endpoint, maskedAttr }));
                        return responseMap;
                    }
                case SUCCESS:
                    {
                        return responseMap;
                    }
            }
        } catch (Exception ex) {
            if (!quiet) {
                Logger logger = GuiUtil.getLogger();
                logger.severe(GuiUtil.getCommonMessage("LOG_REQUEST_RESULT", new Object[] { exitCode, endpoint, maskedAttr }));
                if (logger.isLoggable(Level.FINEST)) {
                    logger.log(Level.FINEST, "response.getResponseBody(): {0}", response.getResponseBody());
                }
            }
            if (handlerCtx != null) {
                // instead of dumping the exception on screen.
                if (throwException) {
                    if ("".equals(message)) {
                        GuiUtil.handleException(handlerCtx, ex);
                    } else {
                        GuiUtil.handleError(handlerCtx, message);
                    }
                }
            } else {
                // if this is called by other java handler, we tell the called handle the exception.
                if ("".equals(message)) {
                    throw new RuntimeException(ex);
                } else {
                    throw new RuntimeException(message, ex);
                }
            }
        }
    }
    return null;
}
Also used : HashMap(java.util.HashMap) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) ExitCode(org.glassfish.api.ActionReport.ExitCode) ArrayList(java.util.ArrayList) NodeList(org.w3c.dom.NodeList) List(java.util.List) Logger(java.util.logging.Logger) HashMap(java.util.HashMap) Map(java.util.Map) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) TreeMap(java.util.TreeMap) IOException(java.io.IOException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) SAXException(org.xml.sax.SAXException)

Example 3 with ExitCode

use of org.glassfish.api.ActionReport.ExitCode in project Payara by payara.

the class RestUtil method hasWarning.

public static boolean hasWarning(Map responseMap) {
    if (responseMap.get("data") != null) {
        String exitCodeStr = (String) ((Map) responseMap.get("data")).get("exit_code");
        ExitCode exitCode = (exitCodeStr != null) ? ExitCode.valueOf(exitCodeStr) : ExitCode.SUCCESS;
        return (exitCode == ExitCode.WARNING);
    }
    return false;
}
Also used : ExitCode(org.glassfish.api.ActionReport.ExitCode)

Example 4 with ExitCode

use of org.glassfish.api.ActionReport.ExitCode in project Payara by payara.

the class RestartHttpListenersCommand method execute.

@Override
public void execute(AdminCommandContext context) {
    ActionReport report = context.getActionReport();
    boolean isAll = all != null && all.booleanValue();
    if (isAll && target == null) {
        ExitCode exitCode = ClusterOperationUtil.replicateCommand("restart-http-listeners", FailurePolicy.Ignore, FailurePolicy.Ignore, FailurePolicy.Error, domain.getAllTargets(), context, new ParameterMap(), locator);
        report.setActionExitCode(exitCode);
    }
    if (report.hasFailures()) {
        return;
    }
    if (target != null && isAll) {
        report.setMessage("--all used together with --target and is ignored.");
        report.setActionExitCode(ExitCode.WARNING);
    }
    if (target == null) {
        target = SystemPropertyConstants.DAS_SERVER_NAME;
    }
    Config config = targetUtil.getConfig(target);
    for (NetworkListener listener : config.getNetworkConfig().getNetworkListeners().getNetworkListener()) {
        try {
            if (!"admin-listener".equals(listener.getName())) {
                service.restartNetworkListener(listener, 10, TimeUnit.SECONDS);
            }
        } catch (Exception ex) {
            report.setMessage(MessageFormat.format("Failed to restart listener {0}, {1}", listener.getName(), (ex.getMessage() == null ? "No reason given" : ex.getMessage())));
            report.setActionExitCode(ExitCode.FAILURE);
            report.setFailureCause(ex);
            return;
        }
        if (!report.hasFailures() && !report.hasWarnings()) {
            report.setActionExitCode(ExitCode.SUCCESS);
        }
    }
}
Also used : Config(com.sun.enterprise.config.serverbeans.Config) ExitCode(org.glassfish.api.ActionReport.ExitCode) ParameterMap(org.glassfish.api.admin.ParameterMap) ActionReport(org.glassfish.api.ActionReport) NetworkListener(org.glassfish.grizzly.config.dom.NetworkListener)

Example 5 with ExitCode

use of org.glassfish.api.ActionReport.ExitCode in project Payara by payara.

the class CompositeUtil method executeCommand.

/**
 * Execute an <code>AdminCommand</code> with the specified parameters.
 *
 * @param command
 * @param parameters
 * @param throwBadRequest (vs. NOT_FOUND)
 * @param throwOnWarning  (vs.ignore warning)
 * @return
 */
public ActionReporter executeCommand(Subject subject, String command, ParameterMap parameters, Status status, boolean includeFailureMessage, boolean throwOnWarning, boolean managed) {
    RestActionReporter ar = ResourceUtil.runCommand(command, parameters, subject, managed);
    ExitCode code = ar.getActionExitCode();
    if (code.equals(ExitCode.FAILURE) || (code.equals(ExitCode.WARNING) && throwOnWarning)) {
        Throwable t = ar.getFailureCause();
        if (t instanceof SecurityException) {
            throw new WebApplicationException(Response.status(Status.UNAUTHORIZED).build());
        }
        if (includeFailureMessage) {
            throw new WebApplicationException(Response.status(status).entity(ar.getCombinedMessage()).build());
        } else {
            throw new WebApplicationException(status);
        }
    }
    return ar;
}
Also used : RestActionReporter(org.glassfish.admin.rest.utils.xml.RestActionReporter) WebApplicationException(javax.ws.rs.WebApplicationException) ExitCode(org.glassfish.api.ActionReport.ExitCode)

Aggregations

ExitCode (org.glassfish.api.ActionReport.ExitCode)10 RestActionReporter (org.glassfish.admin.rest.utils.xml.RestActionReporter)6 ActionReport (org.glassfish.api.ActionReport)6 WebApplicationException (javax.ws.rs.WebApplicationException)3 ActionReportResult (org.glassfish.admin.rest.results.ActionReportResult)3 OptionsResult (org.glassfish.admin.rest.results.OptionsResult)2 ParameterMap (org.glassfish.api.admin.ParameterMap)2 ConfigBean (org.jvnet.hk2.config.ConfigBean)2 TransactionFailure (org.jvnet.hk2.config.TransactionFailure)2 Config (com.sun.enterprise.config.serverbeans.Config)1 IOException (java.io.IOException)1 ArrayList (java.util.ArrayList)1 HashMap (java.util.HashMap)1 List (java.util.List)1 Map (java.util.Map)1 TreeMap (java.util.TreeMap)1 Logger (java.util.logging.Logger)1 MultivaluedHashMap (javax.ws.rs.core.MultivaluedHashMap)1 MultivaluedMap (javax.ws.rs.core.MultivaluedMap)1 Response (javax.ws.rs.core.Response)1