use of org.xwiki.job.Job in project xwiki-platform by xwiki.
the class ExtensionManagerScriptServiceTest method testOverwriteAllowedNamespaces.
@Test
public void testOverwriteAllowedNamespaces() throws Throwable {
InstallRequest installRequest = this.scriptService.createInstallRequest("extension", "version", "namespace");
// Indicate all extensions of type "test" should be installed on root
((ScriptExtensionRewriter) installRequest.getRewriter()).installExtensionTypeOnRootNamespace("test");
// Allow redirect on root
installRequest.setRootModificationsAllowed(true);
Job job = this.scriptService.install(installRequest);
if (job == null) {
throw this.scriptService.getLastError();
}
job.join();
List<LogEvent> errors = job.getStatus().getLog().getLogsFrom(LogLevel.WARN);
if (!errors.isEmpty()) {
throw errors.get(0).getThrowable();
}
// Validate
InstalledExtensionRepository repository = mocker.getInstance(InstalledExtensionRepository.class);
assertNotNull(repository.getInstalledExtension("extension", null));
}
use of org.xwiki.job.Job in project xwiki-platform by xwiki.
the class DocumentsDeletingListenerTest method testCancel.
@Test
public void testCancel() throws Exception {
Request request = mock(Request.class);
Job job = mock(Job.class);
JobStatus status = mock(JobStatus.class);
when(job.getRequest()).thenReturn(request);
when(request.isInteractive()).thenReturn(true);
when(job.getStatus()).thenReturn(status);
Map<EntityReference, EntitySelection> concernedEntities = new HashMap<>();
DocumentReference doc1 = new DocumentReference("a", "b", "c1");
concernedEntities.put(doc1, new EntitySelection(doc1));
XarInstalledExtension ext1 = mock(XarInstalledExtension.class);
when(ext1.getId()).thenReturn(new ExtensionId("ext1"));
when(repository.getXarInstalledExtensions(doc1)).thenReturn(Arrays.asList(ext1));
InterruptedException e = new InterruptedException();
doThrow(e).when(status).ask(any(), anyLong(), any());
// Test
DocumentsDeletingEvent event = mock(DocumentsDeletingEvent.class);
mocker.getComponentUnderTest().onEvent(event, job, concernedEntities);
// Check
verify(status, times(1)).ask(any(), eq(5L), eq(TimeUnit.MINUTES));
verify(event).cancel(eq("Question has been interrupted."));
verify(mocker.getMockedLogger()).warn("Confirm question has been interrupted.");
}
use of org.xwiki.job.Job in project xwiki-platform by xwiki.
the class JobsResourceImpl method executeJob.
@Override
public JobStatus executeJob(String jobType, boolean async, JobRequest restJobRequest) throws XWikiRestException {
// TODO: provide extension point to decide of the access depending on the job
if (!this.authorization.hasAccess(Right.PROGRAM, null)) {
throw new WebApplicationException(Status.UNAUTHORIZED);
}
// Parse JobRequest
DefaultRequest request = this.factory.toJobRequest(restJobRequest);
if (request == null) {
request = new DefaultRequest();
}
// Start job
Job job;
try {
// Give a few context related values to the job
if (request.getProperty(JobRequestContext.KEY) == null) {
JobRequestContext.set(request, this.xcontextProvider.get());
}
job = this.jobExecutor.execute(jobType, request);
} catch (JobException e) {
throw new XWikiRestException("Failed to start job", e);
}
// Wait for the job end if asked
if (!async) {
try {
job.join();
} catch (InterruptedException e) {
throw new XWikiRestException("The job as been interrupted", e);
}
// Fail the HTTP request if the job failed
if (job.getStatus().getError() != null) {
throw new XWikiRestException("The job failed (" + ExceptionUtils.getRootCauseMessage(job.getStatus().getError()) + ")", job.getStatus().getError());
}
}
// Get job status
org.xwiki.job.event.status.JobStatus status = job.getStatus();
// Convert Job status
return this.factory.toRestJobStatus(status, null, true, false, false, null);
}
use of org.xwiki.job.Job in project xwiki-platform by xwiki.
the class FlavorManagerScriptService method searchValidFlavors.
/**
* Start searching for valid flavors.
*
* @param namespace the namespace where to validate the flavors
* @return the {@link Job} searching the flavors
* @since 8.0RC1
*/
public Job searchValidFlavors(String namespace) {
setError(null);
Job job = null;
try {
FlavorSearchRequest flavorRequest = new FlavorSearchRequest();
flavorRequest.setId(getSearchJobId(namespace));
flavorRequest.addNamespace(namespace);
setRightsProperties(flavorRequest);
job = this.jobExecutor.execute(FlavorSearchJob.JOBTYPE, flavorRequest);
} catch (JobException e) {
setError(e);
}
return job;
}
use of org.xwiki.job.Job in project xwiki-platform by xwiki.
the class SaveAction method save.
/**
* Saves the current document, updated according to the parameters sent in the request.
*
* @param context The current request {@link XWikiContext context}.
* @return <code>true</code> if there was an error and the response needs to render an error page,
* <code>false</code> if the document was correctly saved.
* @throws XWikiException If an error occured: cannot communicate with the storage module, or cannot update the
* document because the request contains invalid parameters.
*/
public boolean save(XWikiContext context) throws XWikiException {
XWiki xwiki = context.getWiki();
XWikiRequest request = context.getRequest();
XWikiDocument doc = context.getDoc();
EditForm form = (EditForm) context.getForm();
// Check save session
int sectionNumber = 0;
if (request.getParameter("section") != null && xwiki.hasSectionEdit(context)) {
sectionNumber = Integer.parseInt(request.getParameter("section"));
}
// We need to clone this document first, since a cached storage would return the same object for the
// following requests, so concurrent request might get a partially modified object, or worse, if an error
// occurs during the save, the cached object will not reflect the actual document at all.
doc = doc.clone();
String language = form.getLanguage();
// FIXME Which one should be used: doc.getDefaultLanguage or
// form.getDefaultLanguage()?
// String defaultLanguage = ((EditForm) form).getDefaultLanguage();
XWikiDocument tdoc;
if (doc.isNew() || (language == null) || (language.equals("")) || (language.equals("default")) || (language.equals(doc.getDefaultLanguage()))) {
// Saving the default document translation.
// Need to save parent and defaultLanguage if they have changed
tdoc = doc;
} else {
tdoc = doc.getTranslatedDocument(language, context);
if ((tdoc == doc) && xwiki.isMultiLingual(context)) {
// Saving a new document translation.
tdoc = new XWikiDocument(doc.getDocumentReference());
tdoc.setLanguage(language);
tdoc.setStore(doc.getStore());
} else if (tdoc != doc) {
// Saving an existing document translation (but not the default one).
// Same as above, clone the object retrieved from the store cache.
tdoc = tdoc.clone();
}
}
if (doc.isNew()) {
doc.setLocale(Locale.ROOT);
if (doc.getDefaultLocale() == Locale.ROOT) {
doc.setDefaultLocale(LocaleUtils.toLocale(context.getWiki().getLanguagePreference(context), Locale.ROOT));
}
}
try {
tdoc.readFromTemplate(form.getTemplate(), context);
} catch (XWikiException e) {
if (e.getCode() == XWikiException.ERROR_XWIKI_APP_DOCUMENT_NOT_EMPTY) {
context.put("exception", e);
return true;
}
}
if (sectionNumber != 0) {
XWikiDocument sectionDoc = tdoc.clone();
sectionDoc.readFromForm(form, context);
String sectionContent = sectionDoc.getContent() + "\n";
String content = tdoc.updateDocumentSection(sectionNumber, sectionContent);
tdoc.setContent(content);
tdoc.setComment(sectionDoc.getComment());
tdoc.setMinorEdit(sectionDoc.isMinorEdit());
} else {
tdoc.readFromForm(form, context);
}
// TODO: handle Author
String username = context.getUser();
tdoc.setAuthor(username);
if (tdoc.isNew()) {
tdoc.setCreator(username);
}
// Make sure we have at least the meta data dirty status
tdoc.setMetaDataDirty(true);
// Validate the document if we have xvalidate=1 in the request
if ("1".equals(request.getParameter("xvalidate"))) {
boolean validationResult = tdoc.validate(context);
// If the validation fails we should show the "Inline form" edit mode
if (validationResult == false) {
// Set display context to 'edit'
context.put("display", "edit");
// Set the action used by the "Inline form" edit mode as the context action. See #render(XWikiContext).
context.setAction(tdoc.getDefaultEditMode(context));
// Set the document in the context
context.put("doc", doc);
context.put("cdoc", tdoc);
context.put("tdoc", tdoc);
// Force the "Inline form" edit mode.
getCurrentScriptContext().setAttribute("editor", "inline", ScriptContext.ENGINE_SCOPE);
return true;
}
}
// redirect place-holders that are created when we move pages around.
if (tdoc.getXObject(REDIRECT_CLASS) != null && request.getParameter("XWiki.RedirectClass_0_location") == null) {
tdoc.removeXObjects(REDIRECT_CLASS);
}
// We get the comment to be used from the document
// It was read using readFromForm
xwiki.saveDocument(tdoc, tdoc.getComment(), tdoc.isMinorEdit(), context);
Job createJob = startCreateJob(tdoc.getDocumentReference(), form);
if (createJob != null) {
if (isAsync(request)) {
if (Utils.isAjaxRequest(context)) {
// Redirect to the job status URL of the job we have just launched.
sendRedirect(context.getResponse(), String.format("%s/rest/jobstatus/%s?media=json", context.getRequest().getContextPath(), serializeJobId(createJob.getRequest().getId())));
}
// else redirect normally and the operation will eventually finish in the background.
// Note: It is preferred that async mode is called in an AJAX request that can display the progress.
} else {
// Sync mode, default, wait for the work to finish.
try {
createJob.join();
} catch (InterruptedException e) {
throw new XWikiException(String.format("Interrupted while waiting for template [%s] to be processed when creating the document [%s]", form.getTemplate(), tdoc.getDocumentReference()), e);
}
}
} else {
// Nothing more to do, just unlock the document.
XWikiLock lock = tdoc.getLock(context);
if (lock != null) {
tdoc.removeLock(context);
}
}
return false;
}
Aggregations