Search in sources :

Example 11 with ProcessingException

use of org.eclipse.scout.rt.platform.exception.ProcessingException in project scout.rt by eclipse.

the class MutualExclusionTest method testBlockedJobs.

/**
 * We have 5 jobs that get scheduled simultaneously. The first waits some time so that job2, job3, job4 and job5 get
 * queued. Job1 then enters a blocking condition, which allows job2 to run. But job2 gets rejected by the executor,
 * which allows job3 to run. After job3 completes, job1 is resumed and continues running. After job1 complete, job4
 * gets scheduled. Job4 in turn gets blocked, which prevents job5 from running.
 */
@Test
public void testBlockedJobs() throws java.lang.InterruptedException {
    P_JobManager jobManager = new P_JobManager();
    ExecutorService executorMock = jobManager.getExecutorMock();
    IBean<IJobManager> jobManagerBean = JobTestUtil.replaceCurrentJobManager(jobManager);
    try {
        // synchronized because modified/read by different threads.
        final List<String> protocol = Collections.synchronizedList(new ArrayList<String>());
        // Executor mock
        doAnswer(new Answer<Future>() {

            @Override
            public Future answer(InvocationOnMock invocation) throws Throwable {
                final Runnable runnable = (Runnable) invocation.getArguments()[0];
                // Reject job-2 from being scheduled
                if (runnable instanceof JobFutureTask) {
                    JobFutureTask<?> futureTask = (JobFutureTask<?>) runnable;
                    if ("job-2".equals(futureTask.getJobInput().getName())) {
                        futureTask.reject();
                        return null;
                    }
                }
                s_executor.execute(new NamedThreadRunnable(runnable));
                return null;
            }
        }).when(executorMock).execute(any(Runnable.class));
        final BlockingCountDownLatch job4RunningLatch = new BlockingCountDownLatch(1);
        final IBlockingCondition condition = Jobs.newBlockingCondition(true);
        // Job-1
        IFuture<Void> future1 = Jobs.schedule(new IRunnable() {

            @Override
            public void run() throws Exception {
                // Wait until all 5 jobs are scheduled.
                JobTestUtil.waitForPermitCompetitors(m_clientSession.getModelJobSemaphore(), 5);
                try {
                    protocol.add("running-job-1 (a)");
                    condition.waitFor();
                    protocol.add("running-job-1 (b)");
                } catch (ProcessingException e) {
                    protocol.add("jobException");
                }
                if (ModelJobs.isModelThread()) {
                    protocol.add("running-job-1 (e) [model-thread]");
                }
            }
        }, ModelJobs.newInput(ClientRunContexts.copyCurrent()).withName("job-1").withExecutionHint(JOB_IDENTIFIER).withExceptionHandling(null, false));
        // Job-2
        IFuture<Void> future2 = Jobs.schedule(new IRunnable() {

            @Override
            public void run() throws Exception {
                protocol.add("running-job-2");
            }
        }, ModelJobs.newInput(ClientRunContexts.copyCurrent()).withName("job-2").withExecutionHint(JOB_IDENTIFIER).withExceptionHandling(null, false));
        // Job-3
        IFuture<Void> future3 = Jobs.schedule(new IRunnable() {

            @Override
            public void run() throws Exception {
                protocol.add("running-job-3 (a)");
                condition.setBlocking(false);
                // Wait until job-1 tried to re-acquire the mutex.
                // 4 = job1(re-acquiring), job3(owner), job4, job5
                JobTestUtil.waitForPermitCompetitors(m_clientSession.getModelJobSemaphore(), 4);
                protocol.add("running-job-3 (b)");
            }
        }, ModelJobs.newInput(ClientRunContexts.copyCurrent()).withName("job-3").withExecutionHint(JOB_IDENTIFIER).withExceptionHandling(null, false));
        // Job-4
        IFuture<Void> future4 = Jobs.schedule(new IRunnable() {

            @Override
            public void run() throws Exception {
                protocol.add("running-job-4");
                try {
                    job4RunningLatch.countDownAndBlock();
                } catch (java.lang.InterruptedException e) {
                    protocol.add("job-4 [interrupted]");
                }
            }
        }, ModelJobs.newInput(ClientRunContexts.copyCurrent()).withName("job-4").withExecutionHint(JOB_IDENTIFIER).withExceptionHandling(null, false));
        // Job-5
        IFuture<Void> future5 = Jobs.schedule(new IRunnable() {

            @Override
            public void run() throws Exception {
                protocol.add("running-job-5");
            }
        }, ModelJobs.newInput(ClientRunContexts.copyCurrent()).withName("job-5").withExecutionHint(JOB_IDENTIFIER).withExceptionHandling(null, false));
        assertTrue(job4RunningLatch.await());
        try {
            Jobs.getJobManager().awaitDone(Jobs.newFutureFilterBuilder().andMatchExecutionHint(JOB_IDENTIFIER).toFilter(), 1, TimeUnit.MILLISECONDS);
            // job-4 and job-5 are pending
            fail("timeout expected");
        } catch (TimedOutError e) {
        // NOOP
        }
        // job-4 and job-5 are pending
        assertFalse(Jobs.getJobManager().isDone(Jobs.newFutureFilterBuilder().andMatchExecutionHint(JOB_IDENTIFIER).toFilter()));
        List<String> expectedProtocol = new ArrayList<>();
        expectedProtocol.add("running-job-1 (a)");
        expectedProtocol.add("running-job-3 (a)");
        expectedProtocol.add("running-job-3 (b)");
        expectedProtocol.add("running-job-1 (b)");
        expectedProtocol.add("running-job-1 (e) [model-thread]");
        expectedProtocol.add("running-job-4");
        assertEquals(expectedProtocol, protocol);
        assertFalse(future1.isCancelled());
        assertTrue(future1.isDone());
        assertTrue(future2.isCancelled());
        assertTrue(future2.isDone());
        assertFalse(future3.isCancelled());
        assertTrue(future3.isDone());
        assertFalse(future4.isCancelled());
        assertFalse(future4.isDone());
        assertFalse(future5.isCancelled());
        assertFalse(future5.isDone());
        // cancel job4
        future4.cancel(true);
        awaitDoneElseFail(JOB_IDENTIFIER);
        expectedProtocol.add("job-4 [interrupted]");
        expectedProtocol.add("running-job-5");
        assertEquals(expectedProtocol, protocol);
        assertTrue(Jobs.getJobManager().isDone(Jobs.newFutureFilterBuilder().andMatchExecutionHint(JOB_IDENTIFIER).toFilter()));
        assertTrue(future4.isCancelled());
        assertTrue(future4.isDone());
        assertFalse(future5.isCancelled());
        assertTrue(future5.isDone());
    } finally {
        JobTestUtil.unregisterAndShutdownJobManager(jobManagerBean);
    }
}
Also used : BlockingCountDownLatch(org.eclipse.scout.rt.testing.platform.util.BlockingCountDownLatch) ArrayList(java.util.ArrayList) IJobManager(org.eclipse.scout.rt.platform.job.IJobManager) IRunnable(org.eclipse.scout.rt.platform.util.concurrent.IRunnable) TimedOutError(org.eclipse.scout.rt.platform.util.concurrent.TimedOutError) ProcessingException(org.eclipse.scout.rt.platform.exception.ProcessingException) JobFutureTask(org.eclipse.scout.rt.platform.job.internal.JobFutureTask) ProcessingException(org.eclipse.scout.rt.platform.exception.ProcessingException) AssertionException(org.eclipse.scout.rt.platform.util.Assertions.AssertionException) InvocationOnMock(org.mockito.invocation.InvocationOnMock) IRunnable(org.eclipse.scout.rt.platform.util.concurrent.IRunnable) ExecutorService(java.util.concurrent.ExecutorService) Future(java.util.concurrent.Future) IFuture(org.eclipse.scout.rt.platform.job.IFuture) IBlockingCondition(org.eclipse.scout.rt.platform.job.IBlockingCondition) Test(org.junit.Test)

Example 12 with ProcessingException

use of org.eclipse.scout.rt.platform.exception.ProcessingException in project scout.rt by eclipse.

the class CellTest method testSetValue_validateInalidValue.

@Test
public void testSetValue_validateInalidValue() throws Exception {
    ICellObserver observer = Mockito.mock(ICellObserver.class);
    Cell c = new Cell(observer);
    Object value = new Object();
    when(observer.validateValue(c, value)).thenThrow(new ProcessingException());
    boolean changed = c.setValue(value);
    assertTrue(changed);
    assertSame(value, c.getValue());
    assertFalse(c.isContentValid());
}
Also used : ProcessingException(org.eclipse.scout.rt.platform.exception.ProcessingException) Test(org.junit.Test)

Example 13 with ProcessingException

use of org.eclipse.scout.rt.platform.exception.ProcessingException in project scout.rt by eclipse.

the class AbstractProposalChooser method updateStatus.

protected void updateStatus(IContentAssistFieldDataFetchResult<LOOKUP_KEY> result) {
    if (result != null && result.getException() instanceof FutureCancelledError) {
        return;
    }
    List<? extends ILookupRow<LOOKUP_KEY>> rows = null;
    Throwable exception = null;
    String searchText = null;
    if (result != null) {
        rows = result.getLookupRows();
        exception = result.getException();
        searchText = result.getSearchParam().getSearchQuery();
    }
    if (rows == null) {
        rows = CollectionUtility.emptyArrayList();
    }
    String statusText = null;
    int severity = IStatus.INFO;
    if (exception != null) {
        if (exception instanceof ProcessingException) {
            statusText = ((ProcessingException) exception).getStatus().getMessage();
        } else {
            statusText = exception.getMessage();
        }
        severity = IStatus.ERROR;
    } else if (rows.isEmpty()) {
        if (getContentAssistField().getWildcard().equals(searchText)) {
            statusText = TEXTS.get("SmartFieldNoDataFound");
        } else {
            statusText = TEXTS.get("SmartFieldCannotComplete", (searchText == null) ? ("") : (searchText));
        }
        severity = IStatus.WARNING;
    } else if (rows.size() > m_contentAssistField.getBrowseMaxRowCount()) {
        statusText = TEXTS.get("SmartFieldMoreThanXRows", "" + m_contentAssistField.getBrowseMaxRowCount());
        severity = IStatus.INFO;
    }
    if (statusText != null) {
        setStatus(new Status(statusText, severity));
    } else {
        setStatus(null);
    }
}
Also used : IStatus(org.eclipse.scout.rt.platform.status.IStatus) Status(org.eclipse.scout.rt.platform.status.Status) FutureCancelledError(org.eclipse.scout.rt.platform.util.concurrent.FutureCancelledError) ProcessingException(org.eclipse.scout.rt.platform.exception.ProcessingException)

Example 14 with ProcessingException

use of org.eclipse.scout.rt.platform.exception.ProcessingException in project scout.rt by eclipse.

the class AbstractNumberField method createNumberWithinFormatLimits.

/**
 * Creates a new string which fulfills the given {@link DecimalFormat} max length constraints. An exception is thrown
 * if the number's digits before the decimal point be cut off. It the number's digits after the decimal point would be
 * cut off, no exception is thrown.
 *
 * @param format
 *          The {@link DecimalFormat} holding the constraints: {@link DecimalFormat#getMaximumIntegerDigits()},
 *          {@link DecimalFormat#getMaximumFractionDigits()}.
 * @param curText
 *          The current text (before the modification).
 * @param offset
 *          The offset of the modification relative to the curText parameter.
 * @param replaceLen
 *          How many characters that will be replaced starting at the given offset.
 * @param insertText
 *          The new text that should be inserted at the given replace range.
 * @return String that fulfills the given {@link DecimalFormat} length constraints
 * @throws throws
 *           a {@link ProcessingException} if the number's digits before the decimal point would be cut off
 */
public static String createNumberWithinFormatLimits(DecimalFormat format, String curText, int offset, int replaceLen, String insertText) {
    // When changing this implementation also consider updating the js version!
    if (insertText == null || insertText.length() < 1) {
        insertText = "";
    }
    StringBuilder result = new StringBuilder();
    String futureText = null;
    if (curText == null) {
        futureText = insertText;
    } else {
        StringBuilder docTxt = new StringBuilder(curText.length() + insertText.length());
        docTxt.append(curText);
        docTxt.replace(offset, offset + replaceLen, insertText);
        futureText = docTxt.toString();
    }
    Pattern pat = Pattern.compile("[^1-9" + format.getDecimalFormatSymbols().getZeroDigit() + "]");
    String decimalSeparator = String.valueOf(format.getDecimalFormatSymbols().getDecimalSeparator());
    String[] parts = futureText.split(Pattern.quote(decimalSeparator));
    if (parts.length >= 1) {
        String intPartDigits = pat.matcher(parts[0]).replaceAll("");
        boolean intPartValid = StringUtility.length(intPartDigits) <= format.getMaximumIntegerDigits();
        if (intPartValid) {
            result.append(intPartDigits);
        } else {
            throw new ProcessingException("Do not truncate integer digits!");
        }
    }
    if (parts.length == 2) {
        String fracPartDigits = pat.matcher(parts[1]).replaceAll("");
        boolean fracPartValid = StringUtility.length(fracPartDigits) <= format.getMaximumFractionDigits();
        if (fracPartValid) {
            result.append(decimalSeparator + fracPartDigits);
        } else {
            result.append(decimalSeparator + fracPartDigits.substring(0, format.getMaximumFractionDigits()));
        }
    }
    return result.toString();
}
Also used : Pattern(java.util.regex.Pattern) ProcessingException(org.eclipse.scout.rt.platform.exception.ProcessingException)

Example 15 with ProcessingException

use of org.eclipse.scout.rt.platform.exception.ProcessingException in project scout.rt by eclipse.

the class RemoteFileService method putRemoteFile.

@Override
@RemoteServiceAccessDenied
@SuppressWarnings("findbugs:RV_RETURN_VALUE_IGNORED_BAD_PRACTICE")
public void putRemoteFile(RemoteFile spec) {
    File file = getFileInternal(spec);
    file.getParentFile().mkdirs();
    try (FileOutputStream out = new FileOutputStream(file)) {
        spec.writeData(out);
        file.setLastModified(file.lastModified());
    } catch (Exception e) {
        throw new ProcessingException("error writing file: " + file.getAbsoluteFile(), e);
    }
}
Also used : FileOutputStream(java.io.FileOutputStream) File(java.io.File) RemoteFile(org.eclipse.scout.rt.shared.services.common.file.RemoteFile) IOException(java.io.IOException) ProcessingException(org.eclipse.scout.rt.platform.exception.ProcessingException) ProcessingException(org.eclipse.scout.rt.platform.exception.ProcessingException) RemoteServiceAccessDenied(org.eclipse.scout.rt.shared.servicetunnel.RemoteServiceAccessDenied)

Aggregations

ProcessingException (org.eclipse.scout.rt.platform.exception.ProcessingException)142 IOException (java.io.IOException)48 MessagingException (javax.mail.MessagingException)21 Test (org.junit.Test)19 ArrayList (java.util.ArrayList)17 File (java.io.File)14 VetoException (org.eclipse.scout.rt.platform.exception.VetoException)12 Folder (javax.mail.Folder)10 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)9 RemoteFile (org.eclipse.scout.rt.shared.services.common.file.RemoteFile)9 NoSuchProviderException (java.security.NoSuchProviderException)8 AssertionException (org.eclipse.scout.rt.platform.util.Assertions.AssertionException)8 FileInputStream (java.io.FileInputStream)7 InputStream (java.io.InputStream)7 UnsupportedEncodingException (java.io.UnsupportedEncodingException)7 FileOutputStream (java.io.FileOutputStream)6 Message (javax.mail.Message)6 ByteArrayOutputStream (java.io.ByteArrayOutputStream)5 OutputStream (java.io.OutputStream)5 HashMap (java.util.HashMap)5