Package org.glassfish.admin.rest.utils.xml

Examples of org.glassfish.admin.rest.utils.xml.RestActionReporter


            }
        }
    }

    protected ActionReportResult buildActionReportResult(boolean showEntityValues) {
        RestActionReporter ar = new RestActionReporter();
        ar.setExtraProperties(new Properties());
        ConfigBean entity = (ConfigBean) getEntity();
        if (childID != null) {
            ar.setActionDescription(childID);

        } else if (childModel != null) {
            ar.setActionDescription(childModel.getTagName());
        }
        if (showEntityValues) {
            if (entity != null) {
                ar.getExtraProperties().put("entity", getAttributes(entity));
            }
        }
        OptionsResult optionsResult = new OptionsResult(Util.getResourceName(uriInfo));
        Map<String, MethodMetaData> mmd = getMethodMetaData();
        optionsResult.putMethodMetaData("GET", mmd.get("GET"));
        optionsResult.putMethodMetaData("POST", mmd.get("POST"));
        optionsResult.putMethodMetaData("DELETE", mmd.get("DELETE"));

        ResourceUtil.addMethodMetaData(ar, mmd);
        if (entity != null) {
            ar.getExtraProperties().put("childResources", ResourceUtil.getResourceLinks(entity, uriInfo,
                    ResourceUtil.canShowDeprecatedItems(locatorBridge.getRemoteLocator())));
        }
        ar.getExtraProperties().put("commands", ResourceUtil.getCommandLinks(getCommandResourcesPaths()));

        return new ActionReportResult(ar, entity, optionsResult);
    }
View Full Code Here


        List<Dom> entities = getEntity();
        if (entities == null) {
            return new GetResultList(new ArrayList(), "", new String[][]{}, new OptionsResult(Util.getResourceName(uriInfo)));//empty dom list
        }

        RestActionReporter ar = new RestActionReporter();
        ar.setActionExitCode(ActionReport.ExitCode.SUCCESS);
        ar.setActionDescription("property");
        List properties = new ArrayList();

        for (Dom child : entities) {
            Map<String, String> entry = new HashMap<String, String>();
            entry.put("name", child.attribute("name"));
            entry.put("value", child.attribute("value"));
            String description = child.attribute("description");
            if (description != null) {
                entry.put("description", description);
            }

            properties.add(entry);
        }

        Properties extraProperties = new Properties();
        extraProperties.put("properties", properties);
        ar.setExtraProperties(extraProperties);

        return new ActionReportResult("properties", ar, new OptionsResult(Util.getResourceName(uriInfo)));
    }
View Full Code Here

    private String getEscapedPropertyName(String propName){
        return propName.replaceAll("\\.","\\\\.");
    }

    protected ActionReportResult clearThenSaveProperties(List<Map<String, String>> properties) {
        RestActionReporter ar = new RestActionReporter();
        ar.setActionDescription("property");
        try {
            Map<String, Property> existing = getExistingProperties();
            deleteMissingProperties(existing, properties);
            Map<String, String> data = new LinkedHashMap<String, String>();

            for (Map<String, String> property : properties) {
                Property existingProp = existing.get(property.get("name"));
                String escapedName = getEscapedPropertyName(property.get("name"));
                String value = property.get("value");
                String description = property.get("description");
                final String unescapedValue = value.replaceAll("\\\\", "");

                // the prop name can not contain .
                // need to remove the . test when http://java.net/jira/browse/GLASSFISH-15418  is fixed
                boolean canSaveDesc = property.get("name").indexOf(".") == -1;

                if ((existingProp == null) || !unescapedValue.equals(existingProp.getValue())) {
                    data.put(escapedName, property.get("value"));
                    if (canSaveDesc && (description != null)) {
                        data.put(escapedName + ".description", description);
                    }
                }

                //update the description only if not null/blank
                if ((description != null) && (existingProp != null)) {
                     if (!"".equals(description) && (!description.equals(existingProp.getDescription()))) {
                        if (canSaveDesc) {
                            data.put(escapedName + ".description", description);
                        }
                    }
                }
            }

            if (!data.isEmpty()) {
                Util.applyChanges(data, uriInfo, getSubject());
            }

            String successMessage = localStrings.getLocalString("rest.resource.update.message",
                    "\"{0}\" updated successfully.", new Object[]{uriInfo.getAbsolutePath()});

            ar.setSuccess();
            ar.setMessage(successMessage);
        } catch (Exception ex) {
            if (ex.getCause() instanceof ValidationException) {
                ar.setFailure();
                ar.setFailureCause(ex);
                ar.setMessage(ex.getLocalizedMessage());
            } else {
                throw new WebApplicationException(ex, Response.Status.INTERNAL_SERVER_ERROR);
            }
        }
View Full Code Here

        return Response.ok().entity(responseBody).build();
    }

    protected Response accepted(String command, ParameterMap parameters, URI childUri) {
        CommandRunner cr = Globals.getDefaultHabitat().getService(CommandRunner.class);
        final RestActionReporter ar = new RestActionReporter();
        final CommandRunner.CommandInvocation commandInvocation =
                cr.getCommandInvocation(command, ar, getSubject()).
                parameters(parameters);
        String jobId = DetachedCommandHelper.invokeAsync(commandInvocation);
        return Response
View Full Code Here

    @GET
    @Path("domain{path:.*}")
    @Produces({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML,"text/html;qs=2"})
    public Response getChildNodes(@PathParam("path")List<PathSegment> pathSegments) {
        Response.ResponseBuilder responseBuilder = Response.status(OK);
        RestActionReporter ar = new RestActionReporter();
        ar.setActionDescription("Monitoring Data");
        ar.setMessage("");
        ar.setSuccess();

        String currentInstanceName = System.getProperty("com.sun.aas.instanceName");
        boolean isRunningOnDAS = "server".equals(currentInstanceName); //TODO this needs to come from an API. Check with admin team
        MonitoringRuntimeDataRegistry monitoringRegistry =habitat.getRemoteLocator().getService(MonitoringRuntimeDataRegistry.class);
        TreeNode rootNode = monitoringRegistry.get(currentInstanceName);

        //The pathSegments will always contain "domain". Discard it
        pathSegments = pathSegments.subList(1, pathSegments.size());
        if(!pathSegments.isEmpty()) {
            PathSegment lastSegment = pathSegments.get(pathSegments.size() - 1);
            if(lastSegment.getPath().isEmpty()) { // if there is a trailing '/' (like monitoring/domain/), a spurious pathSegment is added. Discard it.
                pathSegments = pathSegments.subList(0,pathSegments.size() - 1);
            }
        }

        if(!pathSegments.isEmpty() ) {
            String firstPathElement = pathSegments.get(0).getPath();
            if(firstPathElement.equals(currentInstanceName)) { // Query for current instance. Execute it
                //iterate over pathsegments and build a dotted name to look up in monitoring registry
                StringBuilder pathInMonitoringRegistry = new StringBuilder();
                for(PathSegment pathSegment : pathSegments.subList(1,pathSegments.size()) ) {
                        if(pathInMonitoringRegistry.length() > 0 ) {
                            pathInMonitoringRegistry.append('.');
                        }
                        pathInMonitoringRegistry.append(pathSegment.getPath().replaceAll("\\.", "\\\\.")); // Need to escape '.' before passing it to monitoring code
                }

                TreeNode resultNode = pathInMonitoringRegistry.length() > 0 && rootNode != null ?
                        rootNode.getNode(pathInMonitoringRegistry.toString()) : rootNode;
                if (resultNode != null) {
                    List<TreeNode> list = new ArrayList<TreeNode>();
                    if (resultNode.hasChildNodes()) {
                        list.addAll(resultNode.getEnabledChildNodes());
                    } else {
                        list.add(resultNode);
                    }
                    constructEntity(list, ar);
                    responseBuilder.entity(new ActionReportResult(ar));
                } else {
                    //No monitoring data, so nothing to list
                    responseBuilder.status(NOT_FOUND);
                    ar.setFailure();
                    responseBuilder.entity(new ActionReportResult(ar));
                }

            } else { //firstPathElement != currentInstanceName => A proxy request
                if(isRunningOnDAS) { //Attempt to forward to instance if running on Das
                    //TODO validate that firstPathElement corresponds to a valid server name
                    Properties proxiedResponse = new MonitoringProxyImpl().proxyRequest(uriInfo, Util.getJerseyClient(),
                            habitat.getRemoteLocator());
                    ar.setExtraProperties(proxiedResponse);
                    responseBuilder.entity(new ActionReportResult(ar));
                } else { // Not running on DAS and firstPathElement != currentInstanceName => Reject the request as invalid
                    return Response.status(FORBIDDEN).build();
                }
            }
        } else { // Called for /monitoring/domain/
            List<TreeNode> list = new ArrayList<TreeNode>();
            if (rootNode != null) {
                list.add(rootNode); //Add currentInstance to response
            }
            constructEntity(list,  ar);

            if(isRunningOnDAS) { // Add links to instances from the cluster
                Domain domain = habitat.getRemoteLocator().getService(Domain.class);
                Map<String, String> links = (Map<String, String>) ar.getExtraProperties().get("childResources");
                for (Server s : domain.getServers().getServer()) {
                    if (!s.getName().equals("server")) {// add all non 'server' instances
                        links.put(s.getName(), getElementLink(uriInfo, s.getName()));
                    }
                }
View Full Code Here

        return status.toString();
    }

    public void listOfCommands() {
        CommandRunner cr = serviceLocator.getService(CommandRunner.class);
        RestActionReporter ar = new RestActionReporter();
        ParameterMap parameters = new ParameterMap();
        cr.getCommandInvocation("list-commands", ar, getSubject())
                .parameters(parameters).execute();
        List<ActionReport.MessagePart> children = ar.getTopMessagePart().getChildren();
        for (ActionReport.MessagePart part : children) {
            allCommands.add(part.getMessage());

        }
        ar = new RestActionReporter();
        parameters = new ParameterMap();
        parameters.add("DEFAULT", "_");
        cr.getCommandInvocation("list-commands", ar, getSubject()).parameters(parameters).execute();
        children = ar.getTopMessagePart().getChildren();
        for (ActionReport.MessagePart part : children) {
            allCommands.add(part.getMessage());

        }
View Full Code Here

            data = new HashMap<String, String>();
        }
        final RestConfig restConfig = ResourceUtil.getRestConfig(locatorBridge.getRemoteLocator());

        Response.ResponseBuilder responseBuilder = Response.status(UNAUTHORIZED);
        RestActionReporter ar = new RestActionReporter();
        Request grizzlyRequest = request.get();

        // If the call flow reached here, the request has been authenticated by logic in RestAdapater
        // probably with an admin username and password.  The remoteHostName value
        // in the data object is the actual remote host of the end-user who is
        // using the console (or, conceivably, some other client).  We need to
        // authenticate here once again with that supplied remoteHostName to
        // make sure we enforce remote access rules correctly.
        String hostName = data.get("remoteHostName");
        boolean isAuthorized = false;
        boolean responseErrorStatusSet = false;
        Subject subject = null;
        try {
//            subject = ResourceUtil.authenticateViaAdminRealm(Globals.getDefaultHabitat(), grizzlyRequest, hostName);
            subject = ResourceUtil.authenticateViaAdminRealm(locatorBridge.getRemoteLocator(), grizzlyRequest, hostName);
            isAuthorized = ResourceUtil.isAuthorized(locatorBridge.getRemoteLocator(), subject, "domain/rest-sessions/rest-session", "create");
        } catch (RemoteAdminAccessException e) {
            responseBuilder.status(FORBIDDEN);
            responseErrorStatusSet = true;
        } catch (Exception e) {
            ar.setMessage("Error while authenticating " + e);
        }

        if (isAuthorized) {
            responseBuilder.status(OK);

            // Check to see if the username has been set (anonymous user case)
            String username = (String) grizzlyRequest.getAttribute("restUser");
            if (username != null) {
                ar.getExtraProperties().put("username", username);
            }
            ar.getExtraProperties().put("token", sessionManager.createSession(grizzlyRequest.getRemoteAddr(), subject, chooseTimeout(restConfig)));

        } else {
            if ( ! responseErrorStatusSet) {
                responseBuilder.status(UNAUTHORIZED);
            }
View Full Code Here

                if (data.containsKey("name")) {
                    resourceToCreate += data.get("name");
                } else {
                    resourceToCreate += data.get("DEFAULT");
                }
                RestActionReporter actionReport = ResourceUtil.runCommand(commandName, data, getSubject());

                ActionReport.ExitCode exitCode = actionReport.getActionExitCode();
                if (exitCode != ActionReport.ExitCode.FAILURE) {
                    String successMessage =
                        localStrings.getLocalString("rest.resource.create.message",
                        "\"{0}\" created successfully.", resourceToCreate);
                    ActionReportResult arr = ResourceUtil.getActionReportResult(actionReport, successMessage, requestHeaders, uriInfo);
View Full Code Here

        if (entity == null) {//wrong resource
            String errorMessage = localStrings.getLocalString("rest.resource.erromessage.noentity",
                    "Resource not found.");
            return ResourceUtil.getActionReportResult(ActionReport.ExitCode.FAILURE, errorMessage, requestHeaders, uriInfo);
        }
        RestActionReporter ar = new RestActionReporter();
        final String typeKey = (decode(getName(uriInfo.getPath(), '/')));
        ar.setActionDescription(typeKey);

        OptionsResult optionsResult = new OptionsResult(Util.getResourceName(uriInfo));
        Map<String, MethodMetaData> mmd = getMethodMetaData();
        optionsResult.putMethodMetaData("GET", mmd.get("GET"));
        optionsResult.putMethodMetaData("POST", mmd.get("POST"));

        ResourceUtil.addMethodMetaData(ar, mmd);
        ar.getExtraProperties().put("childResources", ResourceUtil.getResourceLinks(getEntity(), uriInfo));
        ar.getExtraProperties().put("commands", ResourceUtil.getCommandLinks(getCommandResourcesPaths()));

        // FIXME:  I'd rather not keep using OptionsResult, but I don't have the time at this point to do it "right."  This is
        // an internal impl detail, so it can wait
        return new ActionReportResult(ar, optionsResult);
    }
View Full Code Here

            } else {
                resourceToCreate = uriInfo.getAbsolutePath() + "/" + resourceToCreate;
            }

            if (null != commandName) {
                RestActionReporter actionReport = ResourceUtil.runCommand(commandName, data, getSubject());

                ActionReport.ExitCode exitCode = actionReport.getActionExitCode();
                if (exitCode != ActionReport.ExitCode.FAILURE) {
                    String successMessage = localStrings.getLocalString("rest.resource.create.message",
                            "\"{0}\" created successfully.", new Object[]{resourceToCreate});
                    return Response.ok().entity(ResourceUtil.getActionReportResult(actionReport, successMessage, requestHeaders, uriInfo)).build();
                }
View Full Code Here

TOP

Related Classes of org.glassfish.admin.rest.utils.xml.RestActionReporter

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.