下面列出了怎么用org.eclipse.ui.console.MessageConsoleStream的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public OutputStream getOutputStream(final OutputStreamType type, OutputRedirection redirect) {
if (!PlatformUI.isWorkbenchRunning()) {
return DEFAULT.getOutputStream(type, redirect);
}
final MessageConsole console = consoleSupplier.get();
boolean silent = redirect == OutputRedirection.SUPPRESS;
if (!silent) {
console.activate();
}
ConsolePlugin.getDefault().getConsoleManager().addConsoles(new IConsole[] { console });
final MessageConsoleStream stream = console.newMessageStream();
getDisplay().asyncExec(() -> {
stream.setColor(toColor(type));
showConsoleView(silent);
});
return stream;
}
/**
* Sets up a {@link CloudSdk} to be used for App Engine standard staging.
*
* @param javaHome JDK/JRE to 1) run {@code com.google.appengine.tools.admin.AppCfg} from
* {@code appengine-tools-api.jar}; and 2) compile JSPs during staging
*/
public AppEngineWebXmlProjectStaging getAppEngineStandardStaging(Path javaHome,
MessageConsoleStream stdoutOutputStream, MessageConsoleStream stderrOutputStream)
throws CloudSdkNotFoundException {
Preconditions.checkState(!initialized, "process wrapper already set up");
initialized = true;
CloudSdk cloudSdk = javaHome == null
? new CloudSdk.Builder().build()
: new CloudSdk.Builder().javaHome(javaHome).build();
ProcessHandler processHandler = LegacyProcessHandler.builder()
.setStartListener(this::storeProcessObject)
.setExitListener(this::recordProcessExitCode)
.addStdOutLineListener(new MessageConsoleWriterListener(stdoutOutputStream))
.addStdErrLineListener(new MessageConsoleWriterListener(stderrOutputStream))
.build();
return AppCfg.builder(cloudSdk).build().newStaging(processHandler);
}
@Override
public IStatus stage(IPath stagingDirectory, IPath safeWorkDirectory,
MessageConsoleStream stdoutOutputStream, MessageConsoleStream stderrOutputStream,
IProgressMonitor monitor) {
SubMonitor subMonitor = SubMonitor.convert(monitor, 100);
boolean result = stagingDirectory.toFile().mkdirs();
if (!result) {
return StatusUtil.error(this, "Could not create staging directory " + stagingDirectory);
}
try {
IPath deployArtifact = getDeployArtifact(safeWorkDirectory, subMonitor.newChild(40));
CloudSdkStagingHelper.stageFlexible(appEngineDirectory, deployArtifact, stagingDirectory,
subMonitor.newChild(60));
return Status.OK_STATUS;
} catch (AppEngineException | CoreException ex) {
return StatusUtil.error(this, Messages.getString("deploy.job.staging.failed"), ex);
} finally {
subMonitor.done();
}
}
/**
* Starts the development server.
*
* @param mode the launch mode (see ILaunchManager.*_MODE constants)
*/
void startDevServer(String mode, RunConfiguration devServerRunConfiguration,
Path javaHomePath, MessageConsoleStream outputStream, MessageConsoleStream errorStream)
throws CoreException, CloudSdkNotFoundException {
BiPredicate<InetAddress, Integer> portInUse = (addr, port) -> {
Preconditions.checkArgument(port >= 0, "invalid port");
return SocketUtil.isPortInUse(addr, port);
};
checkPorts(devServerRunConfiguration, portInUse);
setServerState(IServer.STATE_STARTING);
setMode(mode);
// Create dev app server instance
initializeDevServer(outputStream, errorStream, javaHomePath);
// Run server
try {
devServer.run(devServerRunConfiguration);
} catch (AppEngineException ex) {
Activator.logError("Error starting server: " + ex.getMessage()); //$NON-NLS-1$
stop(true);
}
}
private void initializeDevServer(MessageConsoleStream stdout, MessageConsoleStream stderr,
Path javaHomePath) throws CloudSdkNotFoundException {
MessageConsoleWriterListener stdoutListener = new MessageConsoleWriterListener(stdout);
MessageConsoleWriterListener stderrListener = new MessageConsoleWriterListener(stderr);
// dev_appserver output goes to stderr
cloudSdk = new CloudSdk.Builder()
.javaHome(javaHomePath)
.build();
ProcessHandler processHandler = LegacyProcessHandler.builder()
.addStdOutLineListener(stdoutListener).addStdErrLineListener(stderrListener)
.addStdErrLineListener(serverOutputListener)
.setStartListener(localAppEngineStartListener)
.setExitListener(localAppEngineExitListener)
.async(true)
.build();
DevServers localRun = DevServers.builder(cloudSdk).build();
devServer = localRun.newDevAppServer(processHandler);
moduleToUrlMap.clear();
}
private void setUpProject(IProjectFacetVersion... facetVersions)
throws CloudSdkNotFoundException {
project = projectCreator.withFacets(facetVersions).getProject();
safeWorkDirectory = project.getFolder("safe-work-directory").getLocation();
stagingDirectory = project.getFolder("staging-result").getLocation();
CloudSdk cloudSdk = new CloudSdk.Builder().build();
LegacyProcessHandler processHandler = LegacyProcessHandler.builder()
.addStdOutLineListener(line -> { System.out.println(" [Cloud SDK] " + line); })
.addStdErrLineListener(line -> { System.out.println(" [Cloud SDK] " + line); })
.setExitListener(exitCode -> { cloudSdkExitCode = exitCode; })
.build();
AppEngineWebXmlProjectStaging staging =
AppCfg.builder(cloudSdk).build().newStaging(processHandler);
when(cloudSdkWrapper.getAppEngineStandardStaging(
any(Path.class), any(MessageConsoleStream.class), any(MessageConsoleStream.class)))
.thenReturn(staging);
}
/**
* Installs a Cloud SDK, if the preferences are configured to auto-manage the SDK. Blocks callers
* 1) if the managed SDK is being installed concurrently by others; and 2) until the installation
* is complete.
*
* @param consoleStream stream to which the install output is written
* @param monitor the progress monitor that can also be used to cancel the installation
*/
public IStatus installManagedSdk(MessageConsoleStream consoleStream, IProgressMonitor monitor) {
if (CloudSdkPreferences.isAutoManaging()) {
// We don't check if the Cloud SDK installed but always schedule the install job; such check
// may pass while the SDK is being installed and in an incomplete state.
// Mark installation failure as non-ERROR to avoid job failure reporting dialogs from the
// overly helpful Eclipse UI ProgressManager
CloudSdkInstallJob installJob = new CloudSdkInstallJob(
consoleStream, modifyLock, IStatus.WARNING);
IStatus result = runInstallJob(consoleStream, installJob, monitor);
if (!result.isOK()) {
// recast result as an IStatus.ERROR
return new Status(
IStatus.ERROR,
result.getPlugin(),
result.getCode(),
result.getMessage(),
result.getException());
}
}
return Status.OK_STATUS;
}
@VisibleForTesting
static IStatus runInstallJob(
MessageConsoleStream consoleStream,
CloudSdkModifyJob installJob,
IProgressMonitor cancelMonitor) {
installJob.schedule();
try {
Job.getJobManager().join(CloudSdkInstallJob.CLOUD_SDK_MODIFY_JOB_FAMILY, cancelMonitor);
if (!installJob.join(0, cancelMonitor)) {
return Status.CANCEL_STATUS;
}
return installJob.getResult();
} catch (OperationCanceledException | InterruptedException e) {
installJob.cancel();
// Could wait to verify job termination, but doesn't seem necessary.
return Status.CANCEL_STATUS;
}
}
public OutputStream getConsoleOutputStream(boolean isError) {
final MessageConsoleStream output = messageConsole.newMessageStream();
output.setActivateOnWrite(false);
final int colorId;
if (!isError) {
colorId = SWT.COLOR_BLACK;
} else {
colorId = SWT.COLOR_RED;
}
/* we must set the color in the UI thread */
Runnable runnable = new Runnable() {
public void run() {
org.eclipse.swt.graphics.Color color = Display.getCurrent()
.getSystemColor(colorId);
output.setColor(color);
}
};
Display.getDefault().syncExec(runnable);
return output;
}
private MessageConsoleStream getNewMessageConsoleStream(int msgKind) {
int swtColorId = SWT.COLOR_BLACK;
switch (msgKind) {
case MSG_LOG:
swtColorId = SWT.COLOR_BLACK;
break;
case MSG_INFORMATION:
swtColorId = SWT.COLOR_DARK_GRAY;
break;
case MSG_ERROR:
swtColorId = SWT.COLOR_DARK_MAGENTA;
break;
case MSG_WARNING:
swtColorId = SWT.COLOR_DARK_YELLOW;
break;
case MSG_SUCCESS:
swtColorId = SWT.COLOR_DARK_GREEN;
break;
default:
swtColorId = SWT.COLOR_BLACK;
break;
}
MessageConsoleStream msgConsoleStream = messageConsole.newMessageStream();
msgConsoleStream.setColor(Display.getCurrent().getSystemColor(swtColorId));
return msgConsoleStream;
}
public ConsoleContext ( final MessageConsole messageConsole )
{
this.writerStream = messageConsole.newMessageStream ();
final MessageConsoleStream errorStream = messageConsole.newMessageStream ();
errorStream.setColor ( Display.getDefault ().getSystemColor ( SWT.COLOR_RED ) );
this.errorPrintWriter = new PrintWriter ( new OutputStreamWriter ( errorStream ) );
this.logStream = messageConsole.newMessageStream ();
this.logStream.setColor ( Display.getDefault ().getSystemColor ( SWT.COLOR_GRAY ) );
}
@Override
public OutputStream createErrorStream() {
// Get the error stream for the given console (a stream that print in red).
final MessageConsoleStream errorStream = console.newMessageStream();
Display display = Display.getCurrent();
if (display == null) {
display = Display.getDefault();
}
display.asyncExec(() -> errorStream.setColor(new Color(null, 255, 0, 0)));
return errorStream;
}
@Override
public CommandConsole get(String name, String title) throws IOException {
MessageConsole console = findConsole(name);
MessageConsoleStream stream = console.newMessageStream();
stream.setActivateOnWrite(true);
stream.write("*** " + title + " ***\n");
return new CommandConsoleImpl(console);
}
private void launchDeployJob(IProject project, Credential credential)
throws IOException, CoreException {
sendAnalyticsPing(AnalyticsEvents.APP_ENGINE_DEPLOY);
IPath workDirectory = createWorkDirectory();
DeployPreferences deployPreferences = getDeployPreferences(project);
DeployConsole messageConsole =
MessageConsoleUtilities.createConsole(getConsoleName(deployPreferences.getProjectId()),
new DeployConsole.Factory());
IConsoleManager consoleManager = ConsolePlugin.getDefault().getConsoleManager();
consoleManager.showConsoleView(messageConsole);
ConsoleColorProvider colorProvider = new ConsoleColorProvider();
MessageConsoleStream outputStream = messageConsole.newMessageStream();
MessageConsoleStream errorStream = messageConsole.newMessageStream();
outputStream.setActivateOnWrite(true);
errorStream.setActivateOnWrite(true);
outputStream.setColor(colorProvider.getColor(IDebugUIConstants.ID_STANDARD_OUTPUT_STREAM));
errorStream.setColor(colorProvider.getColor(IDebugUIConstants.ID_STANDARD_ERROR_STREAM));
StagingDelegate stagingDelegate = getStagingDelegate(project);
DeployJob deploy = new DeployJob(deployPreferences, credential, workDirectory,
outputStream, errorStream, stagingDelegate);
messageConsole.setJob(deploy);
deploy.addJobChangeListener(new JobChangeAdapter() {
@Override
public void done(IJobChangeEvent event) {
if (event.getResult().isOK()) {
sendAnalyticsPing(AnalyticsEvents.APP_ENGINE_DEPLOY_SUCCESS);
}
launchCleanupJob();
}
});
deploy.schedule();
}
/**
* @param optionalConfigurationFilesDirectory if not {@code null}, searches optional configuration
* files (such as {@code cron.yaml}) in this directory and deploys them together
*/
public IStatus deploy(IPath stagingDirectory, Path credentialFile,
DeployPreferences deployPreferences, IPath optionalConfigurationFilesDirectory,
MessageConsoleStream stdoutOutputStream, IProgressMonitor monitor) {
if (monitor.isCanceled()) {
throw new OperationCanceledException();
}
SubMonitor progress = SubMonitor.convert(monitor, 1);
progress.setTaskName(Messages.getString("task.name.deploy.project")); //$NON-NLS-1$
try {
List<File> files =
computeDeployables(stagingDirectory, optionalConfigurationFilesDirectory);
List<Path> deployables = new ArrayList<>();
for (File file : files) {
deployables.add(file.toPath());
}
DeployConfiguration configuration =
DeployPreferencesConverter.toDeployConfiguration(deployPreferences, deployables);
try {
Deployment deployment =
cloudSdkProcessWrapper.getAppEngineDeployment(credentialFile, stdoutOutputStream);
deployment.deploy(configuration);
} catch (AppEngineException ex) {
return StatusUtil.error(this, "Error deploying project: " + ex.getMessage(), ex);
}
return cloudSdkProcessWrapper.getExitStatus();
} finally {
progress.worked(1);
}
}
/**
* Sets up a {@link CloudSdk} to be used for App Engine deploy.
*/
public Deployment getAppEngineDeployment(Path credentialFile,
MessageConsoleStream normalOutputStream) throws CloudSdkNotFoundException {
Preconditions.checkNotNull(credentialFile, "credential required for deploying");
Preconditions.checkArgument(Files.exists(credentialFile), "non-existing credential file");
Preconditions.checkState(!initialized, "process wrapper already set up");
initialized = true;
CloudSdk cloudSdk = new CloudSdk.Builder().build();
Gcloud gcloud = Gcloud.builder(cloudSdk)
.setCredentialFile(credentialFile.toFile().toPath())
.setMetricsEnvironment(CloudToolsInfo.METRICS_NAME, CloudToolsInfo.getToolsVersion())
.setShowStructuredLogs("always") // turns on gcloud structured log
.setOutputFormat("json") // Deploy result will be in JSON.
.build();
// Gcloud sends structured deploy result (in JSON format) to stdout, so prepare to capture that.
stdOutCaptor = StringBuilderProcessOutputLineListener.newListenerWithNewlines();
// Gcloud sends structured gcloud logs (in JSON format) to stderr, so prepare to capture them.
gcloudErrorMessageCollector = new GcloudStructuredLogErrorMessageCollector();
ProcessHandler processHandler = LegacyProcessHandler.builder()
.setStartListener(this::storeProcessObject)
.setExitListener(this::recordProcessExitCode)
// Gcloud sends normal operation output to stderr.
.addStdErrLineListener(new MessageConsoleWriterListener(normalOutputStream))
.addStdErrLineListener(gcloudErrorMessageCollector)
.addStdOutLineListener(stdOutCaptor)
.build();
return gcloud.newDeployment(processHandler);
}
/**
* @param workDirectory temporary work directory the job can safely use (e.g., for creating and
* copying various files to stage and deploy)
*/
public DeployJob(DeployPreferences deployPreferences, Credential credential, IPath workDirectory,
MessageConsoleStream stdoutOutputStream, MessageConsoleStream stderrOutputStream,
StagingDelegate stager) {
super(Messages.getString("deploy.job.name")); //$NON-NLS-1$
Preconditions.checkNotNull(deployPreferences.getProjectId());
Preconditions.checkArgument(!deployPreferences.getProjectId().isEmpty());
this.deployPreferences = deployPreferences;
this.credential = credential;
this.workDirectory = workDirectory;
this.stdoutOutputStream = stdoutOutputStream;
this.stderrOutputStream = stderrOutputStream;
this.stager = stager;
}
@Test
public void testSetJavaHome() throws CloudSdkNotFoundException {
setUpAppEngineStandard8Project();
Path javaHome = Paths.get("/some/path");
StagingDelegate delegate = new StandardStagingDelegate(project, javaHome, cloudSdkWrapper);
delegate.stage(stagingDirectory, safeWorkDirectory, null, null,
new NullProgressMonitor());
verify(cloudSdkWrapper).getAppEngineStandardStaging(
eq(javaHome), any(MessageConsoleStream.class), any(MessageConsoleStream.class));
}
public CloudSdkModifyJob(MessageConsoleStream consoleStream, ReadWriteLock cloudSdkLock, int failureSeverity) {
super(Messages.getString("configuring.cloud.sdk")); // $NON-NLS-1$
this.consoleStream = consoleStream != null ? consoleStream : createNewMessageConsole();
this.cloudSdkLock = cloudSdkLock;
this.failureSeverity = failureSeverity;
setRule(MUTEX_RULE);
}
@VisibleForTesting
MessageConsoleStream createNewMessageConsole() {
MessageConsole console = MessageConsoleUtilities.getMessageConsole(
Messages.getString("configuring.cloud.sdk"), // $NON-NLS-1$
null /* imageDescriptor */);
setProperty(IProgressConstants.ACTION_PROPERTY, new ShowConsoleViewAction(console));
return console.newMessageStream();
}
/**
* Return the console output stream. Instantiate if necessary.
* @return the output stream to console
*/
private MessageConsoleStream getConsoleStream() {
if (consoleStream == null) {
consoleStream = getConsole().newMessageStream();
}
return consoleStream;
}
/**
* Prints error message to the console.
*
* @param message error message to print
*/
public static void printError(final String message) {
final Display display = PlatformUI.getWorkbench().getDisplay();
final MessageConsoleStream consoleStream = getConsoleStream();
final Color color = new Color(display, new RGB(255, 0, 0));
consoleStream.setColor(color);
consoleStream.println(message);
}
/**
* getErrorConsoleStream
*
* @return
*/
MessageConsoleStream getErrorConsoleStream()
{
errorConsoleStream = getConsoleStream(errorConsoleStream, ConsoleThemer.CONSOLE_ERROR);
errorConsoleStream.setColor(new Color(null, 255,0,0));
return errorConsoleStream;
}
/**
* getWarningConsoleStream
*
* @return
*/
MessageConsoleStream getWarningConsoleStream()
{
warningConsoleStream = getConsoleStream(warningConsoleStream, ConsoleThemer.CONSOLE_WARNING);
warningConsoleStream.setColor(new Color(null, 255, 255, 0));
return warningConsoleStream;
}
public MessageConsoleStream getLogStream ()
{
return this.logStream;
}
private FakeModifyJob(IStatus result) {
super(mock(MessageConsoleStream.class), modifyLock);
this.result = result;
}
@Test
public void testConsoleNotCreatedIfGiven() {
new FakeModifyJob(mock(MessageConsoleStream.class));
assertNull(findAutoCreatedConsole());
}
@Test
public void testNoActionPropertyIfConsoleGiven() {
Job job = new FakeModifyJob(mock(MessageConsoleStream.class));
Object actionProperty = job.getProperty(IProgressConstants.ACTION_PROPERTY);
assertNull(actionProperty);
}
private FakeModifyJob(boolean blockOnStart) {
super(mock(MessageConsoleStream.class), readWriteLock);
this.blockOnStart = blockOnStart;
}
private FakeModifyJob(MessageConsoleStream consoleStream) {
super(consoleStream, readWriteLock);
blockOnStart = false;
}