Search in sources :

Example 1 with Payload

use of org.glassfish.api.admin.Payload in project Payara by payara.

the class RemoteRestAdminCommand method executeRemoteCommand.

/**
 * Actually execute the remote command.
 */
private void executeRemoteCommand(final ParameterMap params) throws CommandException {
    doHttpCommand(getCommandURI(), "POST", new HttpCommand() {

        @Override
        public void prepareConnection(final HttpURLConnection urlConnection) throws IOException {
            try {
                if (useSse()) {
                    urlConnection.addRequestProperty("Accept", MEDIATYPE_SSE);
                } else {
                    urlConnection.addRequestProperty("Accept", MEDIATYPE_JSON + "; q=0.8, " + MEDIATYPE_MULTIPART + "; q=0.9");
                }
            } catch (CommandException cex) {
                throw new IOException(cex.getLocalizedMessage(), cex);
            }
            // add any user-specified headers
            for (Header h : requestHeaders) {
                urlConnection.addRequestProperty(h.getName(), h.getValue());
            }
            // Write data
            ParamsWithPayload pwp;
            if (doUpload) {
                urlConnection.setChunkedStreamingMode(0);
                pwp = new ParamsWithPayload(outboundPayload, params);
            } else {
                pwp = new ParamsWithPayload(null, params);
            }
            ProprietaryWriter writer = ProprietaryWriterFactory.getWriter(pwp);
            if (logger.isLoggable(Level.FINER)) {
                logger.log(Level.FINER, "Writer to use {0}", writer.getClass().getName());
            }
            writer.writeTo(pwp, urlConnection);
        }

        @Override
        public void useConnection(final HttpURLConnection urlConnection) throws CommandException, IOException {
            String resultMediaType = urlConnection.getContentType();
            if (logger.isLoggable(Level.FINER)) {
                logger.log(Level.FINER, "Result type is {0}", resultMediaType);
                logger.log(Level.FINER, "URL connection is {0}", urlConnection.getClass().getName());
            }
            if (resultMediaType != null && resultMediaType.startsWith(MEDIATYPE_SSE)) {
                String instanceId = null;
                boolean retryableCommand = false;
                try {
                    logger.log(Level.FINEST, "Response is SSE - about to read events");
                    closeSse = false;
                    ProprietaryReader<GfSseEventReceiver> reader = new GfSseEventReceiverProprietaryReader();
                    GfSseEventReceiver eventReceiver = reader.readFrom(urlConnection.getInputStream(), resultMediaType);
                    GfSseInboundEvent event;
                    do {
                        event = eventReceiver.readEvent();
                        if (event != null) {
                            if (logger.isLoggable(Level.FINEST)) {
                                logger.log(Level.FINEST, "Event: {0}", event.getName());
                            }
                            fireEvent(event.getName(), event);
                            if (AdminCommandState.EVENT_STATE_CHANGED.equals(event.getName())) {
                                AdminCommandState acs = event.getData(AdminCommandState.class, MEDIATYPE_JSON);
                                if (acs.getId() != null) {
                                    instanceId = acs.getId();
                                    if (logger.isLoggable(Level.FINEST)) {
                                        logger.log(Level.FINEST, "Command instance ID: {0}", instanceId);
                                    }
                                }
                                if (acs.getState() == AdminCommandState.State.COMPLETED || acs.getState() == AdminCommandState.State.RECORDED || acs.getState() == AdminCommandState.State.REVERTED) {
                                    if (acs.getActionReport() != null) {
                                        setActionReport(acs.getActionReport());
                                    }
                                    closeSse = true;
                                    if (!acs.isOutboundPayloadEmpty()) {
                                        logger.log(Level.FINEST, "Romote command holds data. Must load it");
                                        downloadPayloadFromManaged(instanceId);
                                    }
                                } else if (acs.getState() == AdminCommandState.State.FAILED_RETRYABLE) {
                                    logger.log(Level.INFO, strings.get("remotecommand.failedretryable", acs.getId()));
                                    if (acs.getActionReport() != null) {
                                        setActionReport(acs.getActionReport());
                                    }
                                    closeSse = true;
                                } else if (acs.getState() == AdminCommandState.State.RUNNING_RETRYABLE) {
                                    logger.log(Level.FINEST, "Command stores checkpoint and is retryable");
                                    retryableCommand = true;
                                }
                            }
                        }
                    } while (event != null && !eventReceiver.isClosed() && !closeSse);
                    if (closeSse) {
                        try {
                            eventReceiver.close();
                        } catch (Exception exc) {
                        }
                    }
                } catch (IOException ioex) {
                    if (instanceId != null && "Premature EOF".equals(ioex.getMessage())) {
                        if (retryableCommand) {
                            throw new CommandException(strings.get("remotecommand.lostConnection.retryableCommand", new Object[] { instanceId }), ioex);
                        } else {
                            throw new CommandException(strings.get("remotecommand.lostConnection", new Object[] { instanceId }), ioex);
                        }
                    } else {
                        throw new CommandException(ioex.getMessage(), ioex);
                    }
                } catch (Exception ex) {
                    throw new CommandException(ex.getMessage(), ex);
                }
            } else {
                ProprietaryReader<ParamsWithPayload> reader = ProprietaryReaderFactory.getReader(ParamsWithPayload.class, resultMediaType);
                if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_INTERNAL_ERROR) {
                    ActionReport report;
                    if (reader == null) {
                        report = new CliActionReport();
                        report.setActionExitCode(ExitCode.FAILURE);
                        report.setMessage(urlConnection.getResponseMessage());
                    } else {
                        report = reader.readFrom(urlConnection.getErrorStream(), resultMediaType).getActionReport();
                    }
                    setActionReport(report);
                } else {
                    ParamsWithPayload pwp = reader.readFrom(urlConnection.getInputStream(), resultMediaType);
                    if (pwp.getPayloadInbound() == null) {
                        setActionReport(pwp.getActionReport());
                    } else if (resultMediaType.startsWith("multipart/")) {
                        RestPayloadImpl.Inbound inbound = pwp.getPayloadInbound();
                        setActionReport(pwp.getActionReport());
                        if (logger.isLoggable(Level.FINER)) {
                            logger.log(Level.FINER, "------ PAYLOAD ------");
                            Iterator<Payload.Part> parts = inbound.parts();
                            while (parts.hasNext()) {
                                Payload.Part part = parts.next();
                                logger.log(Level.FINER, " - {0} [{1}]", new Object[] { part.getName(), part.getContentType() });
                            }
                            logger.log(Level.FINER, "---- END PAYLOAD ----");
                        }
                        PayloadFilesManager downloadedFilesMgr = new PayloadFilesManager.Perm(fileOutputDir, null, logger, null);
                        try {
                            downloadedFilesMgr.processParts(inbound);
                        } catch (CommandException cex) {
                            throw cex;
                        } catch (Exception ex) {
                            throw new CommandException(ex.getMessage(), ex);
                        }
                    }
                }
            }
        }
    });
    if (actionReport == null) {
        this.output = null;
        throw new CommandException(strings.get("emptyResponse"));
    }
    if (actionReport.getActionExitCode() == ExitCode.FAILURE) {
        throw new CommandException(strings.getString("remote.failure.prefix", "remote failure:") + " " + this.output);
    }
}
Also used : CliActionReport(com.sun.enterprise.admin.remote.reader.CliActionReport) CliActionReport(com.sun.enterprise.admin.remote.reader.CliActionReport) ActionReport(org.glassfish.api.ActionReport) ProprietaryWriter(com.sun.enterprise.admin.remote.writer.ProprietaryWriter) GfSseEventReceiverProprietaryReader(com.sun.enterprise.admin.remote.sse.GfSseEventReceiverProprietaryReader) GfSseEventReceiverProprietaryReader(com.sun.enterprise.admin.remote.sse.GfSseEventReceiverProprietaryReader) ProprietaryReader(com.sun.enterprise.admin.remote.reader.ProprietaryReader) GfSseInboundEvent(com.sun.enterprise.admin.remote.sse.GfSseInboundEvent) GfSseEventReceiver(com.sun.enterprise.admin.remote.sse.GfSseEventReceiver) SSLException(javax.net.ssl.SSLException) JsonObject(javax.json.JsonObject) Payload(org.glassfish.api.admin.Payload) PayloadFilesManager(org.glassfish.admin.payload.PayloadFilesManager)

Example 2 with Payload

use of org.glassfish.api.admin.Payload in project Payara by payara.

the class PayloadFilesManager method processPartsExtended.

/**
 * Returns all Files extracted from the Payload, treating each Part as a
 * separate file, via a Map from each File to its associated Properties.
 *
 * @param inboundPayload Payload containing file data to be extracted
 * @return map from each extracted File to its corresponding Properties
 * @throws java.io.IOException
 */
public Map<File, Properties> processPartsExtended(final Payload.Inbound inboundPayload) throws Exception {
    if (inboundPayload == null) {
        return Collections.EMPTY_MAP;
    }
    final Map<File, Properties> result = new LinkedHashMap<File, Properties>();
    boolean isReportProcessed = false;
    Part possibleUnrecognizedReportPart = null;
    StringBuilder uploadedEntryNames = new StringBuilder();
    for (Iterator<Payload.Part> partIt = inboundPayload.parts(); partIt.hasNext(); ) {
        Payload.Part part = partIt.next();
        DataRequestType drt = DataRequestType.getType(part);
        if (drt != null) {
            result.put(drt.processPart(this, part, part.getName()), part.getProperties());
            isReportProcessed |= (drt == DataRequestType.REPORT);
            uploadedEntryNames.append(part.getName()).append(" ");
        } else {
            if ((!isReportProcessed) && possibleUnrecognizedReportPart == null) {
                possibleUnrecognizedReportPart = part;
            }
        }
    }
    if ((!isReportProcessed) && possibleUnrecognizedReportPart != null) {
        DataRequestType.REPORT.processPart(this, possibleUnrecognizedReportPart, possibleUnrecognizedReportPart.getName());
        isReportProcessed = true;
    }
    postProcessParts();
    return result;
}
Also used : Part(org.glassfish.api.admin.Payload.Part) Part(org.glassfish.api.admin.Payload.Part) Payload(org.glassfish.api.admin.Payload) Properties(java.util.Properties) File(java.io.File) LinkedHashMap(java.util.LinkedHashMap)

Example 3 with Payload

use of org.glassfish.api.admin.Payload in project Payara by payara.

the class AdminAdapter method onMissingResource.

/**
 * Call the service method, and notify all listeners
 *
 * @exception Exception if an error happens during handling of
 *   the request. Common errors are:
 *   <ul><li>IOException if an input/output error occurs and we are
 *   processing an included servlet (otherwise it is swallowed and
 *   handled by the top level error handler mechanism)
 *       <li>ServletException if a servlet throws an exception and
 *  we are processing an included servlet (otherwise it is swallowed
 *  and handled by the top level error handler mechanism)
 *  </ul>
 *  Tomcat should be able to handle and log any other exception ( including
 *  runtime exceptions )
 */
@Override
public void onMissingResource(Request req, Response res) {
    LogHelper.getDefaultLogger().log(Level.FINER, "Received something on {0}", req.getRequestURI());
    LogHelper.getDefaultLogger().log(Level.FINER, "QueryString = {0}", req.getQueryString());
    HttpStatus statusCode = HttpStatus.OK_200;
    String requestURI = req.getRequestURI();
    /*    if (requestURI.startsWith("/__asadmin/ADMINGUI")) {
            super.service(req, res);

        }*/
    ActionReport report = getClientActionReport(requestURI, req);
    // remove the qualifier if necessary
    if (requestURI.indexOf('.') != -1) {
        requestURI = requestURI.substring(0, requestURI.indexOf('.'));
    }
    Payload.Outbound outboundPayload = PayloadImpl.Outbound.newInstance();
    try {
        if (!latch.await(20L, TimeUnit.SECONDS)) {
            report = getClientActionReport(req.getRequestURI(), req);
            report.setActionExitCode(ActionReport.ExitCode.FAILURE);
            report.setMessage("V3 cannot process this command at this time, please wait");
        } else {
            final Subject s = (authenticator == null) ? null : authenticator.loginAsAdmin(req);
            if (s == null) {
                reportAuthFailure(res, report, "adapter.auth.userpassword", "Invalid user name or password", HttpURLConnection.HTTP_UNAUTHORIZED, "WWW-Authenticate", "BASIC");
                return;
            }
            report = doCommand(requestURI, req, report, outboundPayload, s);
        }
    } catch (ProcessHttpCommandRequestException reqEx) {
        report = reqEx.getReport();
        statusCode = reqEx.getResponseStatus();
    } catch (InterruptedException e) {
        report.setActionExitCode(ActionReport.ExitCode.FAILURE);
        report.setMessage("V3 cannot process this command at this time, please wait");
    } catch (Exception e) {
        report.setActionExitCode(ActionReport.ExitCode.FAILURE);
        report.setMessage("Exception while processing command: " + e);
    }
    try {
        res.setStatus(statusCode);
        /*
             * Format the command result report into the first part (part #0) of
             * the outbound payload and set the response's content type based
             * on the payload's.  If the report is the only part then the
             * stream will be written as content type text/something and
             * will contain only the report.  If the payload already has
             * content - such as files to be downloaded, for example - then the
             * content type of the payload reflects its multi-part nature and
             * an implementation-specific content type will be set in the response.
             */
        ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
        report.writeReport(baos);
        ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
        final Properties reportProps = new Properties();
        reportProps.setProperty("data-request-type", "report");
        outboundPayload.addPart(0, report.getContentType(), "report", reportProps, bais);
        res.setContentType(outboundPayload.getContentType());
        String commandName = req.getRequestURI().substring(getContextRoot().length() + 1);
        // Check session routing for commands that have @ExecuteOn(RuntimeType.SINGLE_INSTANCE)
        if (isSingleInstanceCommand(commandName)) {
            res.addHeader(SET_COOKIE_HEADER, getCookieHeader(req));
        }
        outboundPayload.writeTo(res.getOutputStream());
        res.getOutputStream().flush();
        res.finish();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Also used : HttpStatus(org.glassfish.grizzly.http.util.HttpStatus) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ActionReport(org.glassfish.api.ActionReport) Properties(java.util.Properties) Subject(javax.security.auth.Subject) LoginException(javax.security.auth.login.LoginException) RemoteAdminAccessException(org.glassfish.internal.api.RemoteAdminAccessException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IOException(java.io.IOException) ByteArrayInputStream(java.io.ByteArrayInputStream) Payload(org.glassfish.api.admin.Payload)

Example 4 with Payload

use of org.glassfish.api.admin.Payload in project Payara by payara.

the class DeployerImpl method deploy.

@Override
public String deploy(File file, String... params) throws GlassFishException {
    String[] newParams = new String[params.length + 1];
    System.arraycopy(params, 0, newParams, 0, params.length);
    newParams[params.length] = file.getAbsolutePath();
    CommandExecutorImpl executer = habitat.getService(CommandExecutorImpl.class);
    try {
        String command = "deploy";
        ActionReport actionReport = executer.createActionReport();
        ParameterMap commandParams = executer.getParameters(command, newParams);
        org.glassfish.api.admin.CommandRunner.CommandInvocation inv = executer.getCommandRunner().getCommandInvocation(command, actionReport, kernelIdentity.getSubject());
        inv.parameters(commandParams);
        // set outputbound payload if --retrieve option is specified.
        Payload.Outbound outboundPayload = null;
        String retrieveOpt = commandParams.getOne("retrieve");
        File retrieve = retrieveOpt != null ? new File(retrieveOpt) : null;
        if (retrieve != null && retrieve.exists()) {
            outboundPayload = PayloadImpl.Outbound.newInstance();
            inv.outbound(outboundPayload);
        }
        inv.execute();
        // extract the outbound payload.
        if (outboundPayload != null) {
            extractPayload(outboundPayload, actionReport, retrieve);
        }
        return actionReport.getResultType(String.class);
    } catch (CommandException e) {
        throw new GlassFishException(e);
    }
}
Also used : GlassFishException(org.glassfish.embeddable.GlassFishException) ParameterMap(org.glassfish.api.admin.ParameterMap) CommandException(org.glassfish.api.admin.CommandException) ActionReport(org.glassfish.api.ActionReport) Payload(org.glassfish.api.admin.Payload) File(java.io.File)

Example 5 with Payload

use of org.glassfish.api.admin.Payload in project Payara by payara.

the class MultipartProprietaryWriter method writeTo.

@Override
public void writeTo(final Object entity, final HttpURLConnection urlConnection) throws IOException {
    Payload.Outbound payload = null;
    ParameterMap parameters = null;
    ActionReport ar = null;
    if (entity instanceof ParamsWithPayload) {
        ParamsWithPayload pwp = (ParamsWithPayload) entity;
        payload = pwp.getPayloadOutbound();
        parameters = pwp.getParameters();
        ar = pwp.getActionReport();
    } else if (entity instanceof Payload.Outbound) {
        payload = (Payload.Outbound) entity;
    }
    writeTo(payload, parameters, ar, new OutputStream() {

        private OutputStream delegate;

        private OutputStream getDelegate() throws IOException {
            if (delegate == null) {
                delegate = urlConnection.getOutputStream();
            }
            return delegate;
        }

        @Override
        public void write(int b) throws IOException {
            getDelegate().write(b);
        }

        @Override
        public void write(byte[] b) throws IOException {
            getDelegate().write(b);
        }

        @Override
        public void write(byte[] b, int off, int len) throws IOException {
            getDelegate().write(b, off, len);
        }

        @Override
        public void flush() throws IOException {
            getDelegate().flush();
        }

        @Override
        public void close() throws IOException {
            getDelegate().close();
        }
    }, new ContentTypeWriter() {

        @Override
        public void writeContentType(String firstPart, String secondPart, String boundary) {
            StringBuilder ct = new StringBuilder();
            ct.append(firstPart).append('/').append(secondPart);
            if (boundary != null) {
                ct.append("; boundary=").append(boundary);
            }
            urlConnection.addRequestProperty("Content-type", ct.toString());
            urlConnection.setRequestProperty("MIME-Version", "1.0");
        }
    });
}
Also used : OutputStream(java.io.OutputStream) ParameterMap(org.glassfish.api.admin.ParameterMap) IOException(java.io.IOException) ActionReport(org.glassfish.api.ActionReport) Payload(org.glassfish.api.admin.Payload) ParamsWithPayload(com.sun.enterprise.admin.remote.ParamsWithPayload) ParamsWithPayload(com.sun.enterprise.admin.remote.ParamsWithPayload)

Aggregations

Payload (org.glassfish.api.admin.Payload)7 File (java.io.File)4 IOException (java.io.IOException)4 Properties (java.util.Properties)4 ActionReport (org.glassfish.api.ActionReport)4 FileNotFoundException (java.io.FileNotFoundException)2 URI (java.net.URI)2 Map (java.util.Map)2 ParameterMap (org.glassfish.api.admin.ParameterMap)2 Test (org.junit.Test)2 ParamsWithPayload (com.sun.enterprise.admin.remote.ParamsWithPayload)1 CliActionReport (com.sun.enterprise.admin.remote.reader.CliActionReport)1 ProprietaryReader (com.sun.enterprise.admin.remote.reader.ProprietaryReader)1 GfSseEventReceiver (com.sun.enterprise.admin.remote.sse.GfSseEventReceiver)1 GfSseEventReceiverProprietaryReader (com.sun.enterprise.admin.remote.sse.GfSseEventReceiverProprietaryReader)1 GfSseInboundEvent (com.sun.enterprise.admin.remote.sse.GfSseInboundEvent)1 ProprietaryWriter (com.sun.enterprise.admin.remote.writer.ProprietaryWriter)1 ByteArrayInputStream (java.io.ByteArrayInputStream)1 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 OutputStream (java.io.OutputStream)1