javax.batch.operations.BatchRuntimeException Java Examples

The following examples show how to use javax.batch.operations.BatchRuntimeException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ResponseExceptionHandler.java    From spring-batch-rest with Apache License 2.0 6 votes vote down vote up
@ExceptionHandler(BatchRuntimeException.class)
protected ResponseEntity<Object> handleBatchRuntimeException(BatchRuntimeException e, WebRequest request) {
    log.error("Request {} failed with {}", request, e);
    Throwable cause = e.getCause();
    HttpStatus status = HttpStatus.INTERNAL_SERVER_ERROR;
    if (cause instanceof DuplicateJobException
            || cause instanceof JobExecutionAlreadyRunningException
            || cause instanceof JobInstanceAlreadyCompleteException)
        status = HttpStatus.CONFLICT;
    else if (cause instanceof JobParametersInvalidException
        || cause instanceof JobParametersNotFoundException)
        status = HttpStatus.BAD_REQUEST;
    else if (cause instanceof NoSuchJobException
        || cause instanceof NoSuchJobExecutionException
        || cause instanceof NoSuchJobInstanceException)
        status = HttpStatus.NOT_FOUND;

    ApiError apiError = new ApiError(status.toString(), cause.getMessage(), cause.getClass().getSimpleName(), e.getMessage());
    return handleExceptionInternal(e, apiError, new HttpHeaders(), status, request);
}
 
Example #2
Source File: JpaItemReader.java    From incubator-batchee with Apache License 2.0 6 votes vote down vote up
@Override
public void open(final Serializable checkpoint) throws Exception {
    final BeanLocator beanLocator = BeanLocator.Finder.get(locator);

    emProvider = findEntityManager();
    if (parameterProvider != null) {
        paramProvider = beanLocator.newInstance(ParameterProvider.class, parameterProvider);
    }
    if (pageSize != null) {
        page = Integer.parseInt(pageSize, page);
    }
    if (namedQuery == null && query == null) {
        throw new BatchRuntimeException("a query should be provided");
    }
    detach = Boolean.parseBoolean(detachEntities);
    transaction = Boolean.parseBoolean(jpaTransaction);
}
 
Example #3
Source File: BeanIOs.java    From incubator-batchee with Apache License 2.0 6 votes vote down vote up
public static StreamFactory open(final String filePath, final String streamName, final String configuration) throws Exception {
    if (filePath == null) {
        throw new BatchRuntimeException("input can't be null");
    }
    if (streamName == null) {
        throw new BatchRuntimeException("streamName can't be null");
    }
    final StreamFactory streamFactory = StreamFactory.newInstance();
    if (!streamFactory.isMapped(streamName)) {
        final InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(configuration);
        if (is == null) {
            throw new BatchRuntimeException("Can't find " + configuration);
        }
        try {
            streamFactory.load(is);
        } finally {
            is.close();
        }
    }
    return streamFactory;
}
 
Example #4
Source File: Groovys.java    From incubator-batchee with Apache License 2.0 6 votes vote down vote up
public static <T> GroovyInstance<T> newInstance(final Class<T> expected, final String path, final JobContext jobContext, final StepContext stepContext)
        throws IllegalAccessException, InstantiationException {
    if (path == null) {
        throw new BatchRuntimeException("no script configured expected");
    }
    final File script = new File(path);
    if (!script.exists()) {
        throw new BatchRuntimeException("Can't find script: " + path);
    }

    final ClassLoader tccl = Thread.currentThread().getContextClassLoader();
    final GroovyClassLoader loader = new GroovyClassLoader(tccl);

    final Class<?> clazz;
    try {
        clazz = loader.parseClass(script);
    } catch (final IOException e) {
        throw new BatchRuntimeException(e);
    }

    final T delegate = expected.cast(clazz.newInstance());
    injectIfBatcheeIfAvailable(tccl, delegate, jobContext, stepContext);
    return new GroovyInstance<T>(loader, delegate);
}
 
Example #5
Source File: FlatFileItemReader.java    From incubator-batchee with Apache License 2.0 6 votes vote down vote up
@Override
public void open(final Serializable checkpoint) throws Exception {
    if (input == null) {
        throw new BatchRuntimeException("Can't find any input");
    }
    final File file = new File(input);
    if (!file.exists()) {
        throw new BatchRuntimeException("'" + input + "' doesn't exist");
    }
    if (lineMapper != null) {
        mapper = BeanLocator.Finder.get(locator).newInstance(LineMapper.class, lineMapper);
    } else {
        mapper = null;
    }

    if (commentStr == null) {
        commentStr = "#";
    }
    comments = commentStr.split(",");

    reader = new BufferedReader(new FileReader(file));
    super.open(checkpoint);
}
 
Example #6
Source File: FlatFileItemWriter.java    From incubator-batchee with Apache License 2.0 6 votes vote down vote up
@Override
public void open(final Serializable checkpoint) throws Exception {
    if (output == null) {
        throw new BatchRuntimeException("Can't find any output");
    }
    final File file = new File(output);
    if (!file.getParentFile().exists() && !file.getParentFile().mkdirs()) {
        throw new BatchRuntimeException("Can't create parent for " + output);
    }
    if (lineSeparator == null) {
        lineSeparator = System.getProperty("line.separator", "\n");
    } else if ("\\n".equals(lineSeparator)) {
        lineSeparator = "\n";
    } else if ("\\r\\n".equals(lineSeparator)) {
        lineSeparator = "\r\n";
    }

    writer = new TransactionalWriter(file, encoding, checkpoint);
}
 
Example #7
Source File: StaxItemReader.java    From incubator-batchee with Apache License 2.0 6 votes vote down vote up
@Override
public void open(final Serializable checkpoint) throws Exception {
    if (input == null) {
        throw new BatchRuntimeException("input should be set");
    }
    if (tag == null) {
        throw new BatchRuntimeException("tag should be set");
    }
    if (marshallingPackage == null && marshallingClasses == null) {
        throw new BatchRuntimeException("marshallingPackage should be set");
    }

    unmarshaller = JAXBContextFactory.getJaxbContext(marshallingPackage, marshallingClasses).createUnmarshaller();
    final InputStream is = findInput();
    if (is == null) {
        throw new BatchRuntimeException("Can't find input '" + input + "'");
    }

    reader = XMLInputFactory.newInstance().createXMLEventReader(is);

    super.open(checkpoint);
}
 
Example #8
Source File: JAXBContextFactory.java    From incubator-batchee with Apache License 2.0 6 votes vote down vote up
public static JAXBContext getJaxbContext(final String marshallingPackage, final String marshallingClasses) throws JAXBException {
    if (marshallingPackage != null) {
        return JAXBContext.newInstance(marshallingPackage);
    }

    final String[] classesStr = marshallingClasses.split(",");
    final Class<?>[] classes = new Class<?>[classesStr.length];
    final ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
    for (int i = 0; i < classes.length; i++) {
        try {
            classes[i] = contextClassLoader.loadClass(classesStr[i]);
        } catch (final ClassNotFoundException e) {
            throw new BatchRuntimeException(e);
        }
    }
    return JAXBContext.newInstance(classes);
}
 
Example #9
Source File: JobExecutionControllerTest.java    From spring-batch-rest with Apache License 2.0 5 votes vote down vote up
private void assertJobExecutionExceptionToStatusMapping(JobExecutionException cause, HttpStatus expectedStatus) throws Exception {
    when(adHocStarter.start(any(JobConfig.class))).thenThrow(new BatchRuntimeException("msg", cause));
    mockMvc.perform(post("/jobExecutions").contentType(APPLICATION_JSON).content("{\"name\":\"foo\"}"))
            .andExpect(status().is(expectedStatus.value()))
            .andExpect(content().string(String.format("{\"status\":\"%s\",\"message\":\"%s\",\"exception\":\"%s\",\"detail\":\"%s\"}",
                    expectedStatus.toString(), cause.getMessage(), cause.getClass().getSimpleName(), "msg")));
}
 
Example #10
Source File: JBatchController.java    From incubator-batchee with Apache License 2.0 5 votes vote down vote up
private void view(final HttpServletRequest req, final String name) {
    req.setAttribute("name", name);
    req.setAttribute("view", "view");

    // we copy the logic from jbatch module since the GUI is not (yet?) linked to our impl
    final ClassLoader tccl = Thread.currentThread().getContextClassLoader();
    final String relativePath = "META-INF/batch-jobs/" + name + ".xml";
    final InputStream stream = tccl.getResourceAsStream(relativePath);
    if (stream == null) {
        throw new BatchRuntimeException(new FileNotFoundException("Cannot find an XML for " + name));
    }

    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    int r;
    try {
        while ((r = stream.read()) != -1) {
            baos.write(r);
        }
    } catch (final IOException e) {
        throw new BatchRuntimeException(new FileNotFoundException("Cannot find an XML for " + name));
    }

    req.setAttribute("content", new String(baos.toByteArray())
                                .replace("&","&amp;")
                                .replace("<", "&lt;")
                                .replace(">", "&gt;")
                                .replace("\"", "&quot;")
                                .replace("'", "&apos;"));
}
 
Example #11
Source File: JdbcConnectionConfiguration.java    From incubator-batchee with Apache License 2.0 5 votes vote down vote up
protected Connection connection() throws Exception {
    if (jndi != null) {
        return DataSource.class.cast(new InitialContext().lookup(jndi)).getConnection();
    }

    try {
        Class.forName(driver);
    } catch (final ClassNotFoundException e) {
        throw new BatchRuntimeException(e);
    }
    return DriverManager.getConnection(url, user, password);
}
 
Example #12
Source File: BatcheeLocator.java    From incubator-batchee with Apache License 2.0 5 votes vote down vote up
@Override
public <T> BeanLocator.LocatorInstance<T> newInstance(final Class<T> expected, final String batchId) {
    if (delegate == null) {
        return null;
    }
    try {
        final Object result = instantiationMethod.invoke(delegate, batchId);
        return new BeanLocator.LocatorInstance<T>(expected.cast(getValue.invoke(result)), Closeable.class.cast(getReleasable.invoke(result)));
    } catch (final Exception e) {
        throw new BatchRuntimeException(e);
    }
}
 
Example #13
Source File: JTASynchronizationService.java    From incubator-batchee with Apache License 2.0 5 votes vote down vote up
@Override
public void afterCompletion(final int status) {
    if (status == Status.STATUS_ROLLEDBACK) {
        delegate.afterRollback();
    } else if (status == Status.STATUS_COMMITTED) {
        delegate.afterCommit();
    } else {
        throw new BatchRuntimeException("Unexpected status " + status);
    }
}
 
Example #14
Source File: JTASynchronizationService.java    From incubator-batchee with Apache License 2.0 5 votes vote down vote up
public JTASynchronizationService(final String jndi) {
    try {
        delegate = TransactionSynchronizationRegistry.class.cast(new InitialContext().lookup(jndi));
    } catch (final NamingException e) {
        throw new BatchRuntimeException(e);
    }
}
 
Example #15
Source File: StaxItemWriter.java    From incubator-batchee with Apache License 2.0 5 votes vote down vote up
@Override
public void open(final Serializable checkpoint) throws Exception {
    if (output == null) {
        throw new BatchRuntimeException("output should be set");
    }
    if (marshallingPackage == null && marshallingClasses == null) {
        throw new BatchRuntimeException("marshallingPackage should be set");
    }
    if (encoding == null) {
        encoding = "UTF-8";
    }
    if (rootTag == null) {
        rootTag = "root";
    }
    if (version == null) {
        version = "1.0";
    }

    marshaller = JAXBContextFactory.getJaxbContext(marshallingPackage, marshallingClasses).createMarshaller();
    final File file = new File(output);
    if (!file.getParentFile().exists() && !file.getParentFile().mkdirs()) {
        throw new BatchRuntimeException("Output parent file can't be created");
    }

    final XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newInstance();
    woodStoxConfig(xmlOutputFactory);

    xmlEventFactory = XMLEventFactory.newFactory();
    txWriter = new TransactionalWriter(file, encoding, checkpoint);
    writer = xmlOutputFactory.createXMLEventWriter(txWriter);

    if (txWriter.position() == 0) {
        writer.add(xmlEventFactory.createStartDocument(encoding, version));
        writer.add(xmlEventFactory.createStartElement("", "", rootTag));
        writer.flush();
    }
}
 
Example #16
Source File: StaxItemReader.java    From incubator-batchee with Apache License 2.0 5 votes vote down vote up
@Override
protected Object doRead() throws Exception {
    XMLEvent xmlEvent;
    boolean found = false;
    while (reader.hasNext()) {
        try {
            xmlEvent = reader.peek();
            if (xmlEvent != null && xmlEvent.isStartElement() && tag.equals(xmlEvent.asStartElement().getName().getLocalPart())) {
                found = true;
                break;
            }
            reader.nextEvent();
        } catch (final XMLStreamException e) {
            // no-op
        }
    }
    if (!found) {
        return null;
    }

    try {
        final Object jaxbObject = unmarshaller.unmarshal(reader);

        if (JAXBElement.class.isInstance(jaxbObject)) {
            JAXBElement jbe = (JAXBElement) jaxbObject;
            return JAXBElement.class.cast(jbe).getValue();
        }
        return jaxbObject;
    } catch (final JAXBException ue) {
        throw new BatchRuntimeException(ue);
    }
}
 
Example #17
Source File: JacksonJSonWriter.java    From incubator-batchee with Apache License 2.0 5 votes vote down vote up
@Override
public void open(final Serializable checkpoint) throws Exception {
    final File outputFile = new File(file);
    if (!outputFile.getParentFile().exists() && !outputFile.getParentFile().mkdirs()) {
        throw new BatchRuntimeException("Can't create " + outputFile.getAbsolutePath());
    }

    final ObjectMapper mapper = Jacksons.newMapper(configuration);

    writer = new TransactionalWriter(outputFile, encoding, checkpoint);
    generator = mapper.getFactory().createGenerator(writer);
    if (fieldNameGeneratorClass != null) {
        if ("default".equals(fieldNameGeneratorClass)) {
            fieldNameGenerator = new DefaultFieldNameGenerator();
        } else {
            fieldNameGenerator = FieldNameGenerator.class.cast(Thread.currentThread().getContextClassLoader().loadClass(fieldNameGeneratorClass).newInstance());
        }
    }

    if (useGlobalWrapper()) {
        if (fieldNameGenerator != null) {
            generator.writeStartObject();
        } else {
            generator.writeStartArray();
        }
    }
}
 
Example #18
Source File: JsonpWriter.java    From incubator-batchee with Apache License 2.0 5 votes vote down vote up
@Override
public void open(final Serializable checkpoint) throws Exception {
    final ClassLoader loader = Thread.currentThread().getContextClassLoader();
    final JsonProvider provider = this.provider == null ? JsonProvider.provider() : JsonProvider.class.cast(loader.loadClass(this.provider));

    final File outputFile = new File(file);
    if (!outputFile.getParentFile().exists() && !outputFile.getParentFile().mkdirs()) {
        throw new BatchRuntimeException("Can't create " + outputFile.getAbsolutePath());
    }

    writer = new TransactionalWriter(outputFile, encoding, checkpoint);
    generator = provider.createGeneratorFactory(buildConfig()).createGenerator(writer);
    if (fieldNameGeneratorClass != null) {
        if ("default".equals(fieldNameGeneratorClass)) {
            fieldNameGenerator = new FieldNameGenerator() {
                private int count = 0;

                @Override
                public String nextName() {
                    return "item" + ++count;
                }
            };
        } else {
            fieldNameGenerator = FieldNameGenerator.class.cast(Thread.currentThread().getContextClassLoader().loadClass(fieldNameGeneratorClass).newInstance());
        }
    }

    if (useGlobalWrapper()) {
        if (fieldNameGenerator != null) {
            generator.writeStartObject();
        } else {
            generator.writeStartArray();
        }
    }
}
 
Example #19
Source File: BeanIOWriter.java    From incubator-batchee with Apache License 2.0 5 votes vote down vote up
@Override
public void open(final Serializable checkpoint) throws Exception {
    if (encoding == null) {
        encoding = "UTF-8";
    }

    final File file = new File(filePath);
    if (!file.getParentFile().exists() && !file.getParentFile().mkdirs()) {
        throw new BatchRuntimeException(file.getParentFile().getAbsolutePath());
    }

    transactionalWriter = new TransactionalWriter(file, encoding, checkpoint);
    writer = BeanIOs.open(filePath, streamName, configuration).createWriter(streamName, transactionalWriter);
}
 
Example #20
Source File: JSefaWriter.java    From incubator-batchee with Apache License 2.0 5 votes vote down vote up
@Override
public void open(final Serializable checkpoint) throws Exception {
    final File f = new File(file);
    if (!f.getParentFile().exists() && !f.getParentFile().mkdirs()) {
        throw new BatchRuntimeException(f.getParentFile().getAbsolutePath());
    }

    serializer = createSerializer();
    transactionalWriter = new TransactionalWriter(f, encoding, checkpoint);
    serializer.open(transactionalWriter);
}
 
Example #21
Source File: ContainerLifecycle.java    From incubator-batchee with Apache License 2.0 5 votes vote down vote up
@Override
public void onFinish(final ITestContext iTestContext) {
    if (container != null) {
        try {
            container.close();
        } catch (final Exception e) {
            throw new BatchRuntimeException(e);
        }
    }
}
 
Example #22
Source File: BatchCDIInjectionExtension.java    From incubator-batchee with Apache License 2.0 5 votes vote down vote up
public BeanManager getBeanManager() {
    if (CDI_1_1_AVAILABLE) {
        try {
            return (BeanManager) CDI_GET_BEAN_MANAGER_METHOD.invoke(CDI_CURRENT_METHOD.invoke(null));
        } catch (Exception e) {
            throw new BatchRuntimeException("unable to resolve BeanManager");
        }
    }

    // fallback if CDI isn't available
    final BeanManagerInfo bmi = getBeanManagerInfo(loader());

    BeanManager result = bmi.finalBm;
    if (result == null && bmi.cdi == null) {
        synchronized (this) {
            result = resolveBeanManagerViaJndi();
            if (result == null) {
                result = bmi.loadTimeBm;
            }
            if (result == null) {
                bmi.cdi = false;
                return null;
            }
            bmi.cdi = true;
            bmi.finalBm = result;
        }
    }

    return result;
}
 
Example #23
Source File: JBatchExceptionMapper.java    From incubator-batchee with Apache License 2.0 4 votes vote down vote up
@Override
public Response toResponse(final BatchRuntimeException e) {
    return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
}