@Test public void testNak() throws Exception { out.expectedMessageCount(0); err.expectedMessageCount(1); try { producerTemplate.sendBody("direct:render-test", "error"); // DeadLetterChannel marks Exception as handled // No failure should be reported } catch (RuntimeCamelException e) { // ok } out.assertIsSatisfied(); err.assertIsSatisfied(); FlowInfo flow = flowManager.findFlow(flowId(err), true); assertEquals("Init: error", flow.getText()); assertEquals("Nak: error", flow.getPartInfos().iterator().next().getText()); }
private boolean processInBody(Exchange exchange, Map<String, Object> properties) { final String inBodyProperty = endpoint.getInBody(); if (inBodyProperty != null) { Object value = exchange.getIn().getBody(); try { value = getEndpoint().getCamelContext().getTypeConverter().mandatoryConvertTo( FacebookEndpointConfiguration.class.getDeclaredField(inBodyProperty).getType(), exchange, value); } catch (Exception e) { exchange.setException(new RuntimeCamelException(String.format( "Error converting value %s to property %s: %s", value, inBodyProperty, e.getMessage()), e)); return false; } LOG.debug("Property [{}] has message body value {}", inBodyProperty, value); properties.put(inBodyProperty, value); } return true; }
@Test public void testEndpointWithoutHttps() throws Exception { // these tests does not run well on Windows if (isPlatform("windows")) { return; } // give Jetty time to startup properly Thread.sleep(1000); MockEndpoint mockEndpoint = resolveMandatoryEndpoint("mock:a", MockEndpoint.class); try { template.sendBodyAndHeader("jetty://http://localhost:" + port1 + "/test", expectedBody, "Content-Type", "application/xml"); fail("expect exception on access to https endpoint via http"); } catch (RuntimeCamelException expected) { } assertTrue("mock endpoint was not called", mockEndpoint.getExchanges().isEmpty()); }
private void doRun(final Exchange exchange, final AsyncCallback callback, IgniteCompute compute) throws Exception { Object job = exchange.getIn().getBody(); if (Collection.class.isAssignableFrom(job.getClass())) { Collection<?> col = (Collection<?>) job; TypeConverter tc = exchange.getContext().getTypeConverter(); Collection<IgniteRunnable> runnables = new ArrayList<>(col.size()); for (Object o : col) { runnables.add(tc.mandatoryConvertTo(IgniteRunnable.class, o)); } compute.run(runnables); } else if (IgniteRunnable.class.isAssignableFrom(job.getClass())) { compute.run((IgniteRunnable) job); } else { throw new RuntimeCamelException(String.format( "Ignite Compute endpoint with RUN executionType is only " + "supported for IgniteRunnable payloads, or collections of them. The payload type was: %s.", job.getClass().getName())); } }
private Message getNextElement() { if (zipInputStream == null) { return null; } try { ZipEntry current = getNextEntry(); if (current != null) { LOGGER.debug("read zipEntry {}", current.getName()); Message answer = new DefaultMessage(); answer.getHeaders().putAll(inputMessage.getHeaders()); answer.setHeader("zipFileName", current.getName()); answer.setHeader(Exchange.FILE_NAME, current.getName()); answer.setBody(new ZipInputStreamWrapper(zipInputStream)); return answer; } else { LOGGER.trace("close zipInputStream"); return null; } } catch (IOException exception) { //Just wrap the IOException as CamelRuntimeException throw new RuntimeCamelException(exception); } }
@SuppressWarnings("unchecked") public <T> T convertTo(Class<T> type, Exchange exchange, Object value) { Object instance = injector.newInstance(); if (instance == null) { throw new RuntimeCamelException("Could not instantiate an instance of: " + type.getCanonicalName()); } // inject parent type converter if (instance instanceof TypeConverterAware) { if (registry instanceof TypeConverter) { TypeConverter parentTypeConverter = (TypeConverter) registry; ((TypeConverterAware) instance).setTypeConverter(parentTypeConverter); } } return useExchange ? (T)ObjectHelper.invokeMethod(method, instance, value, exchange) : (T)ObjectHelper .invokeMethod(method, instance, value); }
@Override public <T> void setParameter(String name, T value) throws RuntimeCamelException { ParameterConfiguration config = getPropertyConfiguration(name); // lets try set the property regardless of if this maps to a valid property name // then if the injection fails we will get a valid error otherwise // lets raise a warning afterwards that we should update the metadata on the endpoint class try { IntrospectionSupport.setProperty(endpoint, name, value); } catch (Exception e) { throw new RuntimeCamelException( "Failed to set property '" + name + "' on " + endpoint + " to value " + value + " due " + e.getMessage(), e); } if (config == null) { warnMissingUriParamOnProperty(name); } }
@Override public Writable create(Object value, TypeConverter typeConverter, Holder<Integer> size) { InputStream is = null; try { is = typeConverter.convertTo(InputStream.class, value); ByteArrayOutputStream bos = new ByteArrayOutputStream(); IOUtils.copyBytes(is, bos, HdfsConstants.DEFAULT_BUFFERSIZE, false); BytesWritable writable = new BytesWritable(); writable.set(bos.toByteArray(), 0, bos.toByteArray().length); size.value = bos.toByteArray().length; return writable; } catch (IOException ex) { throw new RuntimeCamelException(ex); } finally { IOHelper.close(is); } }
public void testCannotBindToParameter() throws Exception { // Create hashmap for testing purpose users.put("charles", new User("Charles", "43")); users.put("claus", new User("Claus", "33")); Exchange out = template.send("direct:in", new Processor() { public void process(Exchange exchange) throws Exception { exchange.setProperty("p1", "abc"); exchange.setProperty("p2", 123); Message in = exchange.getIn(); in.setHeader("users", users); // add users hashmap in.setBody("TheBody"); } }); assertTrue("Should fail", out.isFailed()); assertIsInstanceOf(RuntimeCamelException.class, out.getException()); assertIsInstanceOf(NoTypeConversionAvailableException.class, out.getException().getCause()); }
@Test public void testBridge() throws Exception { String response = template.requestBodyAndHeader("http://localhost:" + port2 + "/test/hello", new ByteArrayInputStream("This is a test".getBytes()), "Content-Type", "application/xml", String.class); assertEquals("Get a wrong response", "/", response); response = template.requestBody("http://localhost:" + port1 + "/hello/world", "hello", String.class); assertEquals("Get a wrong response", "/hello/world", response); try { template.requestBody("http://localhost:" + port2 + "/hello/world", "hello", String.class); fail("Expect exception here!"); } catch (Exception ex) { assertTrue("We should get a RuntimeCamelException", ex instanceof RuntimeCamelException); } }
@Override public boolean hasNext() { try { if (tarInputStream == null) { return false; } boolean availableDataInCurrentEntry = tarInputStream.available() > 0; if (!availableDataInCurrentEntry) { // advance to the next entry. parent = getNextElement(); if (parent == null) { tarInputStream.close(); availableDataInCurrentEntry = false; } else { availableDataInCurrentEntry = true; } } return availableDataInCurrentEntry; } catch (IOException exception) { //Just wrap the IOException as CamelRuntimeException throw new RuntimeCamelException(exception); } }
public void testTransactionRollback() throws Exception { MockEndpoint mock = getMockEndpoint("mock:error"); mock.expectedMessageCount(1); try { template.sendBody("direct:fail", "Hello World"); fail("Should have thrown exception"); } catch (RuntimeCamelException e) { // expected as we fail assertIsInstanceOf(RuntimeCamelException.class, e.getCause()); RollbackExchangeException rollback = assertIsInstanceOf(RollbackExchangeException.class, e.getCause().getCause()); assertEquals("Donkey in Action", rollback.getExchange().getIn().getBody()); } assertMockEndpointsSatisfied(); int count = jdbc.queryForObject("select count(*) from books", Integer.class); assertEquals("Number of books", 1, count); }
public void testRequiredAndNewRollback() throws Exception { try { template.sendBody("direct:requiredAndNewRollback", "Tiger in Action"); } catch (RuntimeCamelException e) { // expeced as we fail assertIsInstanceOf(RuntimeCamelException.class, e.getCause()); assertTrue(e.getCause().getCause() instanceof IllegalArgumentException); assertEquals("We don't have Donkeys, only Camels", e.getCause().getCause().getMessage()); } int count = jdbc.queryForObject("select count(*) from books", Integer.class); assertEquals(new Integer(1), jdbc.queryForObject("select count(*) from books where title = ?", Integer.class, "Tiger in Action")); assertEquals(new Integer(0), jdbc.queryForObject("select count(*) from books where title = ?", Integer.class, "Donkey in Action")); // the tiger in action should be committed, but our 2nd route should rollback assertEquals("Number of books", 2, count); }
public void testInvalidMessage() throws Exception { MockEndpoint mock = getMockEndpoint("mock:invalid"); mock.expectedMessageCount(1); String xml = "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>" + "<user xmlns=\"http://foo.com/bar\">" + " <username>someone</username>" + "</user>"; try { template.sendBody("direct:start", xml); fail("Should have thrown a RuntimeCamelException"); } catch (RuntimeCamelException e) { assertTrue(e.getCause() instanceof SchemaValidationException); // expected } assertMockEndpointsSatisfied(); }
@Test public void testRollback() throws Exception { // will rollback forever so we run 3 times or more rollback.expectedMinimumMessageCount(3); // use requestBody to force a InOut message exchange pattern ( = request/reply) // will send and wait for a response try { template.requestBodyAndHeader(data, "<?xml version=\"1.0\"?><request><status id=\"123\"/></request>", "user", "guest"); fail("Should throw an exception"); } catch (RuntimeCamelException e) { assertTrue("Should timeout", e.getCause() instanceof ExchangeTimedOutException); } rollback.assertIsSatisfied(); }
public void testinvalidThenValidMessage() throws Exception { validEndpoint.expectedMessageCount(2); invalidEndpoint.expectedMessageCount(1); try { template.sendBodyAndHeader("direct:start", "<invalid/>", "foo", "notMatchedHeaderValue"); } catch (RuntimeCamelException e) { // the same as above } Object result = template.requestBodyAndHeader("direct:start", "<valid/>", "foo", "bar"); assertEquals("validResult", result); result = template.requestBodyAndHeader("direct:start", "<valid/>", "foo", "bar"); assertEquals("validResult", result); assertMockEndpointsSatisfied(); }
public void publish() throws IOException { AMQP.BasicProperties properties; byte[] body; try { // To maintain backwards compatibility try the TypeConverter (The DefaultTypeConverter seems to only work on Strings) body = camelExchange.getContext().getTypeConverter().mandatoryConvertTo(byte[].class, camelExchange, message.getBody()); properties = endpoint.getMessageConverter().buildProperties(camelExchange).build(); } catch (NoTypeConversionAvailableException | TypeConversionException e) { if (message.getBody() instanceof Serializable) { // Add the header so the reply processor knows to de-serialize it message.getHeaders().put(RabbitMQEndpoint.SERIALIZE_HEADER, true); properties = endpoint.getMessageConverter().buildProperties(camelExchange).build(); body = serializeBodyFrom(message); } else if (message.getBody() == null) { properties = endpoint.getMessageConverter().buildProperties(camelExchange).build(); body = null; } else { LOG.warn("Could not convert {} to byte[]", message.getBody()); throw new RuntimeCamelException(e); } } publishToRabbitMQ(properties, body); }
@Test public void testHttpRedirectFromCamelRoute() throws Exception { MockEndpoint errorEndpoint = context.getEndpoint("mock:error", MockEndpoint.class); errorEndpoint.expectedMessageCount(1); MockEndpoint resultEndpoint = context.getEndpoint("mock:result", MockEndpoint.class); resultEndpoint.expectedMessageCount(0); try { template.requestBody("direct:start", "Hello World", String.class); fail("Should have thrown an exception"); } catch (RuntimeCamelException e) { HttpOperationFailedException cause = assertIsInstanceOf(HttpOperationFailedException.class, e.getCause()); assertEquals(302, cause.getStatusCode()); } errorEndpoint.assertIsSatisfied(); resultEndpoint.assertIsSatisfied(); }
public void process(Exchange exchange) throws Exception { final String msg = exchange.getIn().getBody(String.class); final String targetChannel = exchange.getIn().getHeader(IrcConstants.IRC_TARGET, String.class); if (!connection.isConnected()) { throw new RuntimeCamelException("Lost connection to " + connection.getHost()); } if (msg != null) { if (isMessageACommand(msg)) { LOG.debug("Sending command: {}", msg); connection.send(msg); } else if (targetChannel != null) { LOG.debug("Sending to: {} message: {}", targetChannel, msg); connection.doPrivmsg(targetChannel, msg); } else { for (IrcChannel channel : endpoint.getConfiguration().getChannels()) { LOG.debug("Sending to: {} message: {}", channel, msg); connection.doPrivmsg(channel.getName(), msg); } } } }
public void testTransactionRollbackWithExchange() throws Exception { Exchange out = template.send("direct:fail", new Processor() { public void process(Exchange exchange) throws Exception { exchange.getIn().setBody("Hello World"); } }); int count = jdbc.queryForObject("select count(*) from books", Integer.class); assertEquals("Number of books", 1, count); assertNotNull(out); Exception e = out.getException(); assertIsInstanceOf(RuntimeCamelException.class, e); assertTrue(e.getCause()instanceof IllegalArgumentException); assertEquals("We don't have Donkeys, only Camels", e.getCause().getMessage()); assertEquals(true, out.getIn().getHeader(Exchange.REDELIVERED)); assertEquals(3, out.getIn().getHeader(Exchange.REDELIVERY_COUNTER)); assertEquals(true, out.getProperty(Exchange.FAILURE_HANDLED)); assertEquals(false, out.getProperty(Exchange.ERRORHANDLER_HANDLED)); }
public void testSecurityConfiguredWithTwoExceptions() throws Exception { // test that we also handles a configuration with 2 or more exceptions MockEndpoint result = getMockEndpoint(RESULT_QUEUE); result.expectedMessageCount(0); MockEndpoint mock = getMockEndpoint(SECURITY_ERROR_QUEUE); mock.expectedMessageCount(1); mock.expectedHeaderReceived(MESSAGE_INFO, "Damm some security error"); try { template.sendBody("direct:a", "I am not allowed to do this"); fail("Should have thrown a GeneralSecurityException"); } catch (RuntimeCamelException e) { assertTrue(e.getCause() instanceof GeneralSecurityException); // expected } MockEndpoint.assertIsSatisfied(result, mock); }
public void testUnhandledException() throws Exception { MockEndpoint result = getMockEndpoint(RESULT_QUEUE); result.expectedMessageCount(0); MockEndpoint mock = getMockEndpoint(ERROR_QUEUE); mock.expectedMessageCount(1); mock.expectedHeaderReceived(MESSAGE_INFO, "Handled exchange with IOException"); try { template.sendBodyAndHeader("direct:a", "Hello IOE", "foo", "something that does not match"); fail("Should have thrown a IOException"); } catch (RuntimeCamelException e) { assertTrue(e.getCause() instanceof IOException); // expected, failure is not handled because predicate doesn't match } MockEndpoint.assertIsSatisfied(result, mock); }
public void testPropertiesComponentMandatory() throws Exception { context.removeComponent("properties"); try { context.addRoutes(new RouteBuilder() { @Override public void configure() throws Exception { from("{{cool.start}}") .to("log:{{cool.start}}?showBodyType=false&showExchangeId={{cool.showid}}") .to("mock:{{cool.result}}"); } }); context.start(); fail("Should throw exception"); } catch (RuntimeCamelException e) { IllegalArgumentException cause = assertIsInstanceOf(IllegalArgumentException.class, e.getCause()); String msg = "PropertiesComponent with name properties must be defined in CamelContext to support property placeholders."; assertTrue(cause.getMessage().startsWith(msg)); } }
@Override public boolean hasNext() { try { if (zipInputStream == null) { return false; } boolean availableDataInCurrentEntry = zipInputStream.available() == 1; if (!availableDataInCurrentEntry) { // advance to the next entry. parent = getNextElement(); if (parent == null) { zipInputStream.close(); availableDataInCurrentEntry = false; } else { availableDataInCurrentEntry = true; } } return availableDataInCurrentEntry; } catch (IOException exception) { //Just wrap the IOException as CamelRuntimeException throw new RuntimeCamelException(exception); } }
@Override public void reset() { // reset by closing and creating a new stream based on the file close(); // reset by creating a new stream based on the file stream = null; if (!file.exists()) { throw new RuntimeCamelException("Cannot reset stream from file " + file); } }
@Test @SuppressWarnings("unchecked") public void testBatchMissingParamAtEnd() throws Exception { try { List<?> data = Arrays.asList(Arrays.asList(9, "stu", "vwx"), Arrays.asList(10, "yza")); template.sendBody("direct:batch", data); fail(); } catch (RuntimeCamelException e) { assertTrue(e.getCause() instanceof UncategorizedSQLException); } assertEquals(new Integer(0), jdbcTemplate.queryForObject("select count(*) from projects where id = 9", Integer.class)); assertEquals(new Integer(0), jdbcTemplate.queryForObject("select count(*) from projects where id = 10", Integer.class)); }
protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { public void configure() { onException(RuntimeCamelException.class).handled(true).to("mock:error"); from("direct:Producer").to("direct:EndpointA"); } }; }
private void enableMultipartFilter(HttpCommonEndpoint endpoint, Server server, String connectorKey) throws Exception { ServletContextHandler context = server.getChildHandlerByClass(ServletContextHandler.class); CamelContext camelContext = this.getCamelContext(); FilterHolder filterHolder = new FilterHolder(); filterHolder.setInitParameter("deleteFiles", "true"); if (ObjectHelper.isNotEmpty(camelContext.getProperty(TMP_DIR))) { File file = new File(camelContext.getProperty(TMP_DIR)); if (!file.isDirectory()) { throw new RuntimeCamelException( "The temp file directory of camel-jetty is not exists, please recheck it with directory name :" + camelContext.getProperties().get(TMP_DIR)); } context.setAttribute("javax.servlet.context.tempdir", file); } // if a filter ref was provided, use it. Filter filter = ((JettyHttpEndpoint) endpoint).getMultipartFilter(); if (filter == null) { // if no filter ref was provided, use the default filter filter = new MultiPartFilter(); } filterHolder.setFilter(new CamelFilterWrapper(filter)); String pathSpec = endpoint.getPath(); if (pathSpec == null || "".equals(pathSpec)) { pathSpec = "/"; } if (endpoint.isMatchOnUriPrefix()) { pathSpec = pathSpec.endsWith("/") ? pathSpec + "*" : pathSpec + "/*"; } addFilter(context, filterHolder, pathSpec); LOG.debug("using multipart filter implementation " + filter.getClass().getName() + " for path " + pathSpec); }
public RestNettyHttpBinding copy() { try { return (RestNettyHttpBinding)this.clone(); } catch (CloneNotSupportedException e) { throw new RuntimeCamelException(e); } }
private void doAffinityRun(final Exchange exchange, final AsyncCallback callback, IgniteCompute compute) throws Exception { IgniteRunnable job = exchange.getIn().getBody(IgniteRunnable.class); String affinityCache = exchange.getIn().getHeader(IgniteConstants.IGNITE_COMPUTE_AFFINITY_CACHE_NAME, String.class); Object affinityKey = exchange.getIn().getHeader(IgniteConstants.IGNITE_COMPUTE_AFFINITY_KEY, Object.class); if (job == null || affinityCache == null || affinityKey == null) { throw new RuntimeCamelException(String.format( "Ignite Compute endpoint with AFFINITY_RUN executionType is only " + "supported for IgniteRunnable payloads, along with an affinity cache and key. The payload type was: %s.", exchange.getIn().getBody().getClass().getName())); } compute.affinityRun(affinityCache, affinityKey, job); }
public static HdfsOutputStream createOutputStream(String hdfsPath, HdfsConfiguration configuration) throws IOException { HdfsOutputStream ret = new HdfsOutputStream(); ret.fileType = configuration.getFileType(); ret.actualPath = hdfsPath; ret.info = new HdfsInfo(ret.actualPath); ret.suffixedPath = ret.actualPath + '.' + configuration.getOpenedSuffix(); if (configuration.isWantAppend() || configuration.isAppend()) { if (!ret.info.getFileSystem().exists(new Path(ret.actualPath))) { configuration.setAppend(false); } else { configuration.setAppend(true); ret.info = new HdfsInfo(ret.suffixedPath); ret.info.getFileSystem().rename(new Path(ret.actualPath), new Path(ret.suffixedPath)); } } else { if (ret.info.getFileSystem().exists(new Path(ret.actualPath))) { //only check if not directory if (!ret.info.getFileSystem().isDirectory(new Path(ret.actualPath))) { if (configuration.isOverwrite()) { ret.info.getFileSystem().delete(new Path(ret.actualPath), true); } else { throw new RuntimeCamelException("The file already exists"); } } } } ret.out = ret.fileType.createOutputStream(ret.suffixedPath, configuration); ret.opened = true; return ret; }
@Override public Object doUnmarshal(Exchange exchange, InputStream stream, Object rootObject) throws IOException { if (rootObject.getClass() != Envelope.class) { throw new RuntimeCamelException("Expected Soap Envelope but got " + rootObject.getClass()); } Envelope envelope = (Envelope) rootObject; Header header = envelope.getHeader(); if (header != null) { List<Object> returnHeaders; List<Object> anyHeaderElements = envelope.getHeader().getAny(); if (null != anyHeaderElements && !(getDataFormat().isIgnoreUnmarshalledHeaders())) { if (getDataFormat().isIgnoreJAXBElement()) { returnHeaders = new ArrayList<Object>(); for (Object headerEl : anyHeaderElements) { returnHeaders.add(JAXBIntrospector.getValue(headerEl)); } } else { returnHeaders = anyHeaderElements; } exchange.getOut().setHeader(SoapJaxbDataFormat.SOAP_UNMARSHALLED_HEADER_LIST, returnHeaders); } } List<Object> anyElement = envelope.getBody().getAny(); if (anyElement.size() == 0) { // No parameter so return null return null; } Object payloadEl = anyElement.get(0); Object payload = JAXBIntrospector.getValue(payloadEl); if (payload instanceof Fault) { Exception exception = createExceptionFromFault((Fault) payload); exchange.setException(exception); return null; } else { return getDataFormat().isIgnoreJAXBElement() ? payload : payloadEl; } }
public XmlVerifierConfiguration copy() { try { return (XmlVerifierConfiguration) clone(); } catch (CloneNotSupportedException e) { throw new RuntimeCamelException(e); } }
@Override protected Object doInvokeMethod(ApiMethod method, Map<String, Object> properties) throws RuntimeCamelException { AbstractGoogleClientRequest request = (AbstractGoogleClientRequest) super.doInvokeMethod(method, properties); try { TypeConverter typeConverter = getEndpoint().getCamelContext().getTypeConverter(); for (Entry<String, Object> p : properties.entrySet()) { IntrospectionSupport.setProperty(typeConverter, request, p.getKey(), p.getValue()); } return request.execute(); } catch (Exception e) { throw new RuntimeCamelException(e); } }
/** * Creates a new instance using a factory created by the provided client configuration * parameters. * * @param params the configuration parameters to use when creating the socket factory * @param camelContext the Camel context */ public SSLContextParametersSecureProtocolSocketFactory(SSLContextParameters params, CamelContext camelContext) { try { this.context = params.createSSLContext(camelContext); this.factory = this.context.getSocketFactory(); } catch (Exception e) { throw new RuntimeCamelException("Error creating the SSLContext.", e); } }
@Override public NettyHttpConfiguration copy() { try { // clone as NettyHttpConfiguration NettyHttpConfiguration answer = (NettyHttpConfiguration) clone(); // make sure the lists is copied in its own instance List<ChannelHandler> encodersCopy = new ArrayList<ChannelHandler>(getEncoders()); answer.setEncoders(encodersCopy); List<ChannelHandler> decodersCopy = new ArrayList<ChannelHandler>(getDecoders()); answer.setDecoders(decodersCopy); return answer; } catch (CloneNotSupportedException e) { throw new RuntimeCamelException(e); } }
@Override public URI getURI() { if (uri == null) { // lazily create the URI which may fail as not all camel uriText are valid URI text try { uri = new URI(uriText); } catch (URISyntaxException e) { throw new RuntimeCamelException(e); } } return uri; }
@Test public void testTimeout() throws Exception { try { // send a in-out with a timeout for 1 sec template.requestBody("activemq:queue:slow?requestTimeout=1000", "Hello World"); fail("Should have timed out with an exception"); } catch (RuntimeCamelException e) { assertTrue("Should have timed out with an exception", e.getCause() instanceof ExchangeTimedOutException); } }