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);
}
}
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;
}
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);
}
}
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);
}
}
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");
}
});
}
Aggregations