Camel-K does not recognize local package - java

I have a RouteBuilder class that is using its own Processor. When running locally in Camel using Maven, it runs fine. However, when I try to use camel-k, it says it cannot find the package. Is there something I need to do?
MyProcessor
package com.test.processor;
import java.io.File;
import org.apache.camel.Exchange;
import org.apache.camel.Message;
import org.apache.camel.Processor;
import org.apache.camel.component.file.GenericFile;
public class MyProcessor implements Processor {
public void process(Exchange exchange) throws Exception {
Message inMsg = exchange.getIn();
Object body = inMsg.getBody();
if (body instanceof File) {
System.out.println("Is a FILE");
} else {
System.out.println("Not a FILE");
}
if (body instanceof GenericFile) {
System.out.println("Is a GF for sure");
GenericFile gf = (GenericFile) body;
String fileName = gf.getFileName();
System.out.println("Filename: " + fileName);
} else {
System.out.println("NOT a GF");
}
}
}
Router
package com.javainuse.route;
import org.apache.camel.builder.RouteBuilder;
import com.test.processor.MyProcessor;
public class SimpleRouteBuilder extends RouteBuilder {
#Override
public void configure() throws Exception {
// Transfer files from one another using a processor
from("file:C:/inputFolder?noop=true")
.process(new MyProcessor())
.to("file:C:/outputFolder")
.setBody().simple("Test")
.log("Test log");
}
}
I am using minikube and run the command:
kamel run SimpleRouteBuilder.java --dev
[1] Exception in thread "main" org.apache.camel.RuntimeCamelException: org.joor.ReflectException: Compilation error: /com/test/route/SimpleRouteBuilder.java:4: error: package com.test.processor does not exist
[1] import com.test.processor.MyProcessor;

This is expected as camel-k does not know where to find the classes for your processor so you have two options:
embed the processor as inner class of your route
package your processor as a maven artifact (you can also use jitpack to avoid having to publish it to a maven repo while testing) and list it as any other dependency

Related

Moving a file from a directory to a success directory or an error directory with Spring Integration

I am trying to implement a Spring Integration class that takes a .xml file parses it and if it's valid move it to an "archived" directory and in case of invalidity move it to an error directory.
import com.nagarro.studentapi.integration.queue.StudentSender;
import com.nagarro.studentapi.util.XmlParser;
import org.aopalliance.aop.Advice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.annotation.InboundChannelAdapter;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.config.EnableIntegration;
import org.springframework.integration.core.MessageSource;
import org.springframework.integration.dsl.IntegrationFlow;
import org.springframework.integration.dsl.IntegrationFlows;
import org.springframework.integration.dsl.Pollers;
import org.springframework.integration.file.FileHeaders;
import org.springframework.integration.file.FileReadingMessageSource;
import org.springframework.integration.file.FileWritingMessageHandler;
import org.springframework.integration.file.filters.SimplePatternFileListFilter;
import org.springframework.integration.file.support.FileExistsMode;
import org.springframework.integration.handler.advice.AbstractRequestHandlerAdvice;
import org.springframework.integration.handler.advice.ExpressionEvaluatingRequestHandlerAdvice;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler;
import org.springframework.messaging.MessagingException;
import java.io.File;
#Configuration
#EnableIntegration
public class IntegrationConfiguration {
private static final String XML = "*.xml";
private static final String STUDENT = "\\student.xml";
#Value("${student-api.xmlPath}")
private String inputPath;
#Value("${student-api.archivedDestination}")
private String successPath;
#Value("${student-api.errorDestination}")
private String errorPath;
#Bean
public MessageChannel messageChannel() {
return new DirectChannel();
}
#Bean
#InboundChannelAdapter(value = "messageChannel")
public MessageSource<File> messageProducer() {
FileReadingMessageSource messageSource = new FileReadingMessageSource();
messageSource.setDirectory(new File(inputPath));
messageSource.setFilter(new SimplePatternFileListFilter(XML));
return messageSource;
}
#Bean
#ServiceActivator(inputChannel = "messageChannel")
public MessageHandler handler() {
FileWritingMessageHandler handler = new FileWritingMessageHandler(new File(successPath));
handler.setFileExistsMode(FileExistsMode.REPLACE);
handler.setExpectReply(false);
return handler;
}
#Bean
public IntegrationFlow integrationFlow(XmlParser xmlParser) {
return IntegrationFlows.from(messageProducer(), spec -> spec.poller(Pollers.fixedDelay(1000)))
.enrichHeaders(h -> h.headerExpression(FileHeaders.ORIGINAL_FILE, "payload"))
.convert(String.class)
.transform((String path) -> xmlParser.parsePath(path))
.handle("xmlParser", "parsePath", e -> e.advice(errorAdvice()))
.get();
}
#Bean
public AbstractRequestHandlerAdvice errorAdvice() {
return new AbstractRequestHandlerAdvice() {
#Override
protected Object doInvoke(ExecutionCallback callback, Object target, Message<?> message) {
File file = message.getHeaders().get(FileHeaders.ORIGINAL_FILE, File.class);
try {
Object result = callback.execute();
file.renameTo(new File(successPath, STUDENT));
System.out.println("File renamed after success");
return result;
}
catch (Exception e) {
file.renameTo(new File(errorPath, STUDENT));
System.out.println("File renamed after failure");
throw e;
}
}
};
}
}
However whenever calback.execute() it's called I get this error and I don't quite understand why.
2022-09-06 18:20:07.971 ERROR 32152 --- [ scheduling-1] o.s.integration.handler.LoggingHandler : org.springframework.messaging.MessageHandlingException: error occurred during processing message in 'MethodInvokingMessageProcessor' [org.springframework.integration.handler.MethodInvokingMessageProcessor#1135e3d6]; nested exception is java.lang.IllegalArgumentException: No candidate methods found for messages., failedMessage=GenericMessage [payload=Student(firstname=John, lastname=Dose, cnp=123, birthDate=2000-12-12, address=Address(street=a, number=1, city=Craiova, country=Romania), grades=[Grade(discipline=a, date=2021-12-12, grade=10), Grade(discipline=b, date=2021-12-12, grade=9)]), headers={....
Although I have a message handler I suspect the reason for this problem is that i do not override the handle method. But i am unsure of how to do it.
You have several problem:
#InboundChannelAdapter and IntegrationFlows.from(messageProducer(). This way you create two independent polling endpoints for the same source.
#ServiceActivator - the endpoint to write has just read file from one of the sources.
There is no connection between #InboundChannelAdapter, your #ServiceActivator expectations and that flow.
You have .transform((String path) -> xmlParser.parsePath(path)) and then immediately after that handle("xmlParser", "parsePath") which looks, essentially the same, but does not make sense since you are going to call the same parsePath() twice, but for different payloads, where the second one is going to be as a result of the first parsePath() call.
Please, revise your logic carefully: right now some of your configuration is misleading and really error-prone. I believe that error you got is because your parsePath() expects a String, but not Student as we see in the payload for that handle().

Why is my Camel JUnit test case producer template not able to send a body?

I am trying to test a route which is like this:
from("s3://bucketName")
.process(exchange -> {exchange.getIn().setHeader(Exchange.FILE_NAME,MY_FILE_NAME);})
.log("File download Successful")
.to("file:" + FILE_PATH).routeId("mys3Route");
I have written my test like this:
#Test
public void testFileMovement() throws Exception {
AdviceWith.adviceWith(context, "mys3Route", a -> {
a.replaceFromWith("mock:s3Location");
a.interceptSendToEndpoint("file:" + FILE_PATH).skipSendToOriginalEndpoint()
.to("mock:anotherLocation");
});
MockEndpoint mockedToEndPoint = getMockEndpoint("mock:anotherLocation");
mockedToEndPoint.setExpectedMessageCount(1);
template.sendBody("mock:s3Location", "Just Text");
mockedToEndPoint.assertIsSatisfied();
Thread.sleep(5000);
}
Whenever I run this as unit test case, I get this error:
org.apache.camel.CamelExecutionException: Exception occurred during >execution on the exchange: Exchange[]
The error seems to be coming up here in: org.apache.camel.impl.engine.DefaultProducerTemplate.extractResultBody(DefaultProducerTemplate.java:591) (which is present in camel dependencies).
Any idea as to what I am doing wrong and how I can rectify it? Any help to resolve and understand this issue is greatly appreciated .
For starters you probably should not replace consumer/From endpoint with MockEndpoint just use direct endpoint. MockEndpoints only support producer endpoints (to) and should not be used as consumer endpoint (from). MockEndpoints are meant to be used as points on your route where you want to do assertions on things like message body, exchange properties, received messages etc.
Secondly if you're using AdviceWith you should set the isUseAdviceWith to true and start the context manually just before you use template.send methods. How this is set varies a bit if you're using spring boot annotations or not. Example below uses just simple CamelTestSupport.
Thirdly you rarely if ever need to use intercept on camel tests, use weaveById, weaveByToURI with replace instead. In this case you're better off just fixing how your file-path and file-name is set by using property-placeholders instead. This way you can just use useOverridePropertiesWithPropertiesComponent and TemporaryFolder feature of junit. Also Apache-commons IO FileUtils is pretty handy if you need to read file-contents of a test file or copy something to a test folder.
Using Thread.Sleep with unit tests is hacky at best and should be avoided. For this case I see no reason why you would use it. RouteId is best placed at the top of the route.
Example:
package com.example;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Properties;
import org.apache.camel.RoutesBuilder;
import org.apache.camel.builder.AdviceWithRouteBuilder;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.test.junit4.CamelTestSupport;
import org.apache.commons.io.FileUtils;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
public class ExampleTest extends CamelTestSupport {
#Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
File outputFolder;
static final String FILE_NAME = "testfile.txt";
#Test
public void testFileMovement() throws Exception {
context.getRouteDefinition("mys3Route")
.adviceWith(context, new AdviceWithRouteBuilder(){
#Override
public void configure() throws Exception {
replaceFromWith("direct:start");
weaveAddLast()
.to("mock:result");
}
});
MockEndpoint resultMockEndpoint = getMockEndpoint("mock:result");
resultMockEndpoint.setExpectedMessageCount(1);
startCamelContext();
template.sendBody("direct:start", "Just Text");
File file = new File(outputFolder, FILE_NAME);
assertEquals(true, file.exists());
String fileContents = FileUtils.readFileToString(file, StandardCharsets.UTF_8);
assertEquals("Just Text", fileContents);
resultMockEndpoint.assertIsSatisfied();
}
#Override
protected RoutesBuilder createRouteBuilder() throws Exception {
return new RouteBuilder(){
#Override
public void configure() throws Exception {
from("s3://bucketName")
.routeId("mys3Route")
.log("File download Successful")
.to("file:{{filepath}}?fileName={{filename}}");
}
};
}
#Override
protected Properties useOverridePropertiesWithPropertiesComponent() {
try {
outputFolder = temporaryFolder.newFolder("output");
} catch (IOException e) {
e.printStackTrace();
}
Properties properties = new Properties();
properties.put("filename", FILE_NAME);
properties.put("filepath", outputFolder.getPath());
return properties;
}
#Override
public boolean isUseAdviceWith() {
return true;
}
}
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io.version}</version>
</dependency>

Spring Resource Inside JAR/WAR

I created a really simple project to test reading a directory or file using getClass().getResource('...').getPath() from STS, Tomcat, and running the JAR/WAR file from the terminal with the embedded Tomcat.
Like I said, the project is simple, here's the code:
package org.example
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.CommandLineRunner
import org.springframework.boot.SpringApplication
import org.springframework.boot.autoconfigure.SpringBootApplication
#SpringBootApplication
class ResourceDemoApplication implements CommandLineRunner {
static void main(String[] args) {
SpringApplication.run ResourceDemoApplication, args
}
#Override
void run(String... arg0) throws Exception {
retrieveDirectory()
}
void retrieveDirectory() {
/*new File(getClass().getResource('/private/folders').getPath()).eachDirRecurse() { dir ->
dir.eachFileMatch(~/.*.txt/) { file ->
println(file.getPath())
}
}*/
println new File(getClass().getResource('/private/folders/').getPath()).isDirectory()
}
}
When this code runs in STS or if I drop it in a running Tomcat instance, it prints true. When I run it as java -jar..., it returns false in the terminal. I have looked at countless examples and I still don't understand how to get this to work properly or as expected. I know that reading files from inside the JAR is different than having access to the file system, but I'm not sure how to get this to work regardless of how it's deployed.
Thank you in advance for the help!
After quite a bit of research and digging into the code, I ended up with this solution:
package org.example
import org.springframework.boot.CommandLineRunner
import org.springframework.boot.SpringApplication
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.core.io.FileSystemResource
import org.springframework.core.io.support.PathMatchingResourcePatternResolver
#SpringBootApplication
class ResourceDemoApplication implements CommandLineRunner {
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver()
static void main(String[] args) {
SpringApplication.run ResourceDemoApplication, args
}
#Override
void run(String... arg0) throws Exception {
retrieveDirectory()
}
void retrieveDirectory() {
List<FileSystemResource> files = resolver.findPathMatchingResources('private/folders/**/example.txt')
files.each { file ->
println file.getInputStream().text
}
}
}
With groovy you don't need to declare types etc... I am doing it for the sake of documentation here to show what's happening in the code. If you do this in Java you will need something like this to replace println file.getInputStream().text:
InputStream is
BufferedReader br
String fileContents
files.each { file ->
is = file.getInputStream()
br = new BufferedReader(new InputStreamReader(is))
String line
fileContents = ""
while((line = br.readLine()) != null) {
fileContents += line
}
println fileContents
println "************************"
br.close()
}

NoClassDefFoundError: com/google/common/reflect/TypeToken

I have been using this api. The API is a Java wrapper for Mailchimp API with maven dependency.
<dependency>
<groupId>com.ecwid</groupId>
<artifactId>ecwid-mailchimp</artifactId>
<version>2.0.1.0</version>
</dependency>
I didn’t have trouble working with their API so far. But now I see this strange exception:
Exception in thread "Timer-2" java.lang.NoClassDefFoundError: com/google/common/reflect/TypeToken
at com.ziprealty.subscription.MailChimpNewsSubscriptionProcessor.updateAllUnSubscribedEmails(MailChimpNewsSubscriptionProcessor.java:84)
at com.ziprealty.job.MailChimpSubscriptionProcessor.processTask(MailChimpSubscriptionProcessor.java:29)
at com.ziprealty.job.JobBase.run(JobBase.java:96)
at java.util.TimerThread.mainLoop(Timer.java:555)
at java.util.TimerThread.run(Timer.java:505)
Caused by: java.lang.ClassNotFoundException: com.google.common.reflect.TypeToken
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1305)
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1157)
... 5 more
And here is the code for updateAllUnSubscribedEmails
public void updateAllUnSubscribedEmails( Date lastRunDate, String brandCode,Logger logger){
logger.log(Level.SEVERE, "Entering mail chimp subscription processor in boardwalk for :" + brandCode);
logger.log(Level.SEVERE, "Last run date is :" + lastRunDate);
System.out.println("Entering mail chimp subscription processor in boardwalk for :" + brandCode);
try {
MailChimpSubscriptionDAO subscriptionDAO = MailChimpSubscriptionDAO.INSTANCE;
MailChimpSubscription subscription= subscriptionDAO.getMailChimpSubscriptionByBrandCode(brandCode);
logger.log(Level.SEVERE,"Subscription object is :"+ subscription);
**ListMembersMethod listMembersMethod= new ListMembersMethod();**
logger.log(Level.SEVERE,"listMembersMethod object is :"+ listMembersMethod);
listMembersMethod.status= MemberStatus.unsubscribed;
logger.log(Level.SEVERE,"listMembersMethod.status object is :"+ listMembersMethod.status);
listMembersMethod.apikey=mailChimpApiKey;
logger.log(Level.SEVERE,"listMembersMethod.apikey object is :"+ listMembersMethod.apikey);
listMembersMethod.id=subscription.getEmailListId();
logger.log(Level.SEVERE,"listMembersMethod.id object is :"+ listMembersMethod.id);
listMembersMethod.since= lastRunDate;
.
.
.
.
} catch (IOException e) {
e.printStackTrace();
System.out.println(e.getMessage());
logger.log(Level.SEVERE, e.getMessage());
} catch (MailChimpException e) {
e.printStackTrace();
System.out.println(e.getMessage());
logger.log(Level.SEVERE, e.getMessage());
}
catch (Exception e){
e.printStackTrace();
System.out.println(e.getMessage());
logger.log(Level.SEVERE, e.getMessage());
}
finally {
logger.log(Level.SEVERE,"Finally block ...Try catch block ended");
}
logger.log(Level.SEVERE,"After finally Try catch block without exception ");
}
The code stops working at this line :
ListMembersMethod listMembersMethod= new ListMembersMethod();
It doesn’t even go to the Exceptions block at all. Only to the finally block.
This is the generated code by Intelij IDEA for the class ListMembersMethod:
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
package com.ecwid.mailchimp.method.v1_3.list;
import com.ecwid.mailchimp.MailChimpAPIVersion;
import com.ecwid.mailchimp.MailChimpMethod.Method;
import com.ecwid.mailchimp.MailChimpObject.Field;
import com.ecwid.mailchimp.method.v1_3.list.HasListIdMethod;
import com.ecwid.mailchimp.method.v1_3.list.ListMembersResult;
import com.ecwid.mailchimp.method.v1_3.list.MemberStatus;
import java.util.Date;
#Method(
name = "listMembers",
version = MailChimpAPIVersion.v1_3
)
public class ListMembersMethod extends HasListIdMethod<ListMembersResult> {
#Field
public MemberStatus status;
#Field
public Date since;
#Field
public Integer start;
#Field
public Integer limit;
public ListMembersMethod() {
}
}
Intelij Idea has also generated the following code for hasHasListIdMethod :
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
package com.ecwid.mailchimp.method.v1_3.list;
import com.ecwid.mailchimp.MailChimpMethod;
import com.ecwid.mailchimp.MailChimpObject.Field;
public abstract class HasListIdMethod<R> extends MailChimpMethod<R> {
#Field
public String id;
public HasListIdMethod() {
}
}
The MailChimpMethod has the following code where it contains TypeToken
:
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
package com.ecwid.mailchimp;
import com.ecwid.mailchimp.MailChimpAPIVersion;
import com.ecwid.mailchimp.MailChimpObject;
import com.ecwid.mailchimp.MailChimpObject.Field;
import com.google.common.reflect.TypeToken;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
public abstract class MailChimpMethod<R> extends MailChimpObject {
private final TypeToken<R> resultTypeToken = new TypeToken(this.getClass()) {
};
#Field
public String apikey;
public MailChimpMethod() {
}
public final MailChimpMethod.Method getMetaInfo() {
for(Class c = this.getClass(); c != null; c = c.getSuperclass()) {
MailChimpMethod.Method a = (MailChimpMethod.Method)c.getAnnotation(MailChimpMethod.Method.class);
if(a != null) {
return a;
}
}
throw new IllegalArgumentException("Neither " + this.getClass() + " nor its superclasses are annotated with " + MailChimpMethod.Method.class);
}
public final Type getResultType() {
Type type = this.resultTypeToken.getType();
if(!(type instanceof Class) && !(type instanceof ParameterizedType) && !(type instanceof GenericArrayType)) {
throw new IllegalArgumentException("Cannot resolve result type: " + this.resultTypeToken);
} else {
return type;
}
}
#Documented
#Retention(RetentionPolicy.RUNTIME)
#Target({ElementType.TYPE})
public #interface Method {
MailChimpAPIVersion version();
String name();
}
}
I would really appreciate your help on this. Couldn't figure out what the fix would be.
The MailChimp API Wrapper 2.0.1.0 depends on Guava 16.0.1 (see mvnrepository.com/artifact/com.ecwid/ecwid-mailchimp/2.0.1.0). The com.google.common.reflect.TypeToken class is part of Guava 16.0.1 (see central.maven.org/maven2/com/google/guava/guava/16.0.1/guava-16.0.1.jar).
Do you use Maven to build your project and if this is the case, can you compile/test your code without issues? Is Guava downloaded for the project? What do you see when running mvn dependency:tree -Dverbose?
It took me sometime but I found the issue. I was working on two independent projects which are dependent on MailChimp API. However, I didn't have the maven dependency on one of the project and that was causing the problem.
So included the maven dependency on both projects, and it worked like a charm!
<dependency>
<groupId>com.ecwid</groupId>
<artifactId>ecwid-mailchimp</artifactId>
<version>2.0.1.0</version>
</dependency>

How to make MongoDB Service Available?

I am developing OSGi Mongodb bundle I have also added the following dependencies
com.mongodb
org.apache.felix.fileinstal
org.amdatu.mongo
org.apache.felix.configadmin
and all the dependency managers but in gogo console I get the following error message
org.amdatu.mongo
org.osgi.service.cm.ManagedServiceFactory(service.pid=org.amdatu.mongo) registered
org.osgi.service.log.LogService service optional unavailable
[11] agenda.mongodb.mongo_gfs
agenda.mongo.inter.AgendaMongo() unregistered
org.amdatu.mongo.MongoDBService service required unavailable
the main problem is MongoDBService is not available I must require this service for solving this problem I have read the book according to them
From a development perspective, everything seems fine, but when you
run the appli‐ cation, it will complain that the MongoDBService is
unavailable. You can figure this out with the dmcommand in the shell.
We did however set up MongoDB on our system and deployed the necessary
dependencies in our runtime. Still, the MongoDBService was unable to
start. How come? This is because the MongoDBService needs some
mandatory configuration in order to know to what database to connect
to. The Amdatu MongoDB Serviceuses the Managed Service Factory pattern
(see Chapter 4), and in order to bootstrap it, we need to supply a
configuration file. In order to supply the configuration file, we need
to create a new folder in our agendaproject. Create a new folder
called load. This is the default name that the runtime will look for
in order to spot configuration files. Next, add an empty text file and
call it something like org.amdatu.mongo-demo.xml. The configuration
file needs at least the following information: dbName=demo
I have also apply this but its still unavailable.
This is interface:
package agenda.mongo.inter;
import java.io.InputStream;
public interface AgendaMongo {
public String store_in_db();
public InputStream getData(Object file_id);
}
This is the implementation for Mongodb:
package agenda.mongodb.gridfs;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.UnknownHostException;
import org.amdatu.mongo.MongoDBService;
import org.bson.types.ObjectId;
import agenda.mongo.inter.AgendaMongo;
import com.mongodb.DB;
import com.mongodb.DBCursor;
import com.mongodb.gridfs.GridFS;
import com.mongodb.gridfs.GridFSDBFile;
import com.mongodb.gridfs.GridFSInputFile;
public class Gridfs_Mongodb implements AgendaMongo{
GridFSInputFile gfsinput=null;
private volatile MongoDBService mongoservice;
public String store_in_db() {
/*try {
GridFS gfsHandler;
gfsHandler = new GridFS(mongoservice.getDB(), "rest_data");// database
File uri = new File("f:\\get1.jpg"); // name and
gfsinput = gfsHandler.createFile(uri);
gfsinput.saveChunks(1000);
gfsinput.setFilename("new file");
gfsinput.save();
//System.out.println(gfsinput.getId());
//save_filepath("file",gfsinput.getId());
Object get_id = gfsinput.getId();//get_filename();
//System.out.println(getData(get_id));
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
//System.out.println("Exception");
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
//System.out.println("Exception");
e.printStackTrace();
}*/
System.out.println("DB:" + mongoservice.getDB());
return mongoservice.getDB()+"";
}
/*
* Retrieving the file
*/
public InputStream getData(Object file_id) {
GridFS gfsPhoto = new GridFS(mongoservice.getDB(), "rest_data");
GridFSDBFile dataOutput = gfsPhoto.findOne((ObjectId) file_id);
DBCursor cursor = gfsPhoto.getFileList();
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
System.out.println(dataOutput);
return dataOutput.getInputStream();
}
void start(){
System.out.println("hello");
System.out.println(store_in_db());
}
}
Here I was just trying to get database name because every thing can be done after that but I t was returning me NULL because MongoDBService is Unavailable.
At this is Activator class
package agenda.mongodb.gridfs;
import org.amdatu.mongo.MongoDBService;
import org.apache.felix.dm.DependencyActivatorBase;
import org.apache.felix.dm.DependencyManager;
import org.osgi.framework.BundleContext;
import agenda.mongo.inter.AgendaMongo;
public class Activator extends DependencyActivatorBase {
#Override
public void init(BundleContext arg0, DependencyManager manager)
throws Exception {
manager.add(createComponent()
.setInterface(AgendaMongo.class.getName(), null)
.setImplementation(Gridfs_Mongodb.class)
.add(createServiceDependency()
.setService(MongoDBService.class)
.setRequired(true)));
}
#Override
public void destroy(BundleContext arg0, DependencyManager arg1)
throws Exception {
// TODO Auto-generated method stub
}
}
The Interface package is an exported package and the implementation package is private.
The configuration file should have a .cfg extension (not .xml).

Categories