org.hibernate.search.bridge.BridgeException: Exception while calling bridge#objectToString - hibernate-search

I am able to insert record and able index them but i am facing an exception while searching
org.hibernate.search.bridge.BridgeException: Exception while calling bridge#objectToString
class: com.edoors.formBean.Hib_cons_Cv
path: cons_cv
I am able search on all coulmn of table except blob column
Field Bridge
public class ByteArrayBridge implements TwoWayStringBridge {
public String objectToString(Object object) {
byte[] data = (byte[]) object;
StringWriter writer = new StringWriter();
InputStream is = null;
try {
is = new ByteArrayInputStream(data);
new AutoDetectParser().parse(is,new WriteOutContentHandler(writer),new Metadata(),new
ParseContext());
return is.toString();
} catch (Exception e) {
System.out.println("Exception "+e);
}
return writer.toString();
}
public Object stringToObject(String string) {
byte[] data=string.getBytes();
Object obj=data;
return obj;
}
}
DAO Class ::
public List searchConsultantByTitle(String jobtitle)
{
List list=null;
Session session = hiberUtil.openSession();
Transaction tx = null;
try{
tx = session.beginTransaction();
FullTextSession fullTextSession = Search.getFullTextSession(session);
QueryBuilder queryBuilder =
fullTextSession.getSearchFactory().buildQueryBuilder().forEntity(Hib_cons_Cv.class).get();
org.apache.lucene.search.Query luceneQuery = null;
luceneQuery =
queryBuilder.keyword().fuzzy().withThreshold(0.7f).onField("cons_cv").matching(jobtitle).createQuery();
FullTextQuery hibernateQuery = fullTextSession.createFullTextQuery(luceneQuery, Hib_cons_Cv.class);
int resultSize = hibernateQuery.getResultSize();
System.out.println(".....resultSize..............................."+resultSize);
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
POJO Class
#Entity
#AnalyzerDef(name = "customanalyzer", tokenizer = #TokenizerDef(factory =
KeywordTokenizerFactory.class), filters = {
#TokenFilterDef(factory = LowerCaseFilterFactory.class),
#TokenFilterDef(factory = SnowballPorterFilterFactory.class, params = {
#Parameter(name = "language", value = "English") }) })
#Indexed
public class Hib_cons_Cv {
#Column(name = "cons_cv", unique = false, nullable = false, length = 59296)
#Lob
#Field(analyze = Analyze.NO, store = Store.YES)
#FieldBridge(impl = ByteArrayBridge.class)
private Blob cons_cv;
//setters and getters
}

I also got this error (with no stack trace). Turned out i put in the wrong field name. It was actually using a field with no bridging.

Related

QueryService in GemFire 8.2.x Function return null values

I have created function to select data from Partition region Individual. When I try to execute the function at client side getting null.
output
[[], null]
public class MySelectPartitionFunction extends FunctionAdapter implements Declarable{
private static final long serialVersionUID = 1L;
#Override
public void execute(FunctionContext context) {
Cache cache = CacheFactory.getAnyInstance();
QueryService queryService = cache.getQueryService();
String qstr = (String) context.getArguments();
try {
Query query = queryService.newQuery(qstr);
RegionFunctionContext rContext = (RegionFunctionContext)context;
SelectResults results = (SelectResults) query.execute(rContext);
context.getResultSender().sendResult((ArrayList) (results).asList());
context.getResultSender().lastResult(null);
} catch (Exception e) {
throw new FunctionException(e);
}
}
#Override
public String getId() {
return getClass().getName();
}
#Override
public boolean hasResult() {
return true;
}
#Override
public boolean isHA() {
return false;
}
public void init(Properties arg0) {
}
}
public class TestFunctionQuery {
public static void main(String[] args) {
ResultCollector rcollector = null;
ClientCache cache;
Region<?, ?> individual;
cache = new ClientCacheFactory().set("name", "ClientWorker").set("cache-xml-file", "xml/clientCache.xml")
.create();
individual = cache.getRegion("Individual");
String qStr = "SELECT * FROM /Individual";
try {
Set keyFilter = new HashSet();
keyFilter.add(1);
rcollector = FunctionService
.onRegion(individual)
.withArgs(qStr)
.withFilter(keyFilter)
.execute("com.xxx.logic.MySelectPartitionFunction");
Object result = rcollector.getResult();
ArrayList resultList = (ArrayList)result;
List queryResults = new ArrayList();
if (resultList.size()!=0) {
for (Object obj: resultList) {
if (obj != null) {
queryResults.addAll((ArrayList)obj);
}
}
}
System.out.println((queryResults));
} catch (FunctionException ex) {
System.out.println("Exception");
}
}
}
gfsh>describe region --name=Individual
..........................................................
Name : Individual
Data Policy : partition
Hosting Members : server2
server1
Non-Default Attributes Shared By Hosting Members
Type | Name | Value
--------- | ---------------- | -----
Region | size | 3
Partition | redundant-copies | 1
I was able to retrieve the record after making changes in Function and client code
#Override
public void execute(FunctionContext context) {
Cache cache = CacheFactory.getAnyInstance();
QueryService queryService = cache.getQueryService();
String qstr = (String) context.getArguments();
try {
Query query = queryService.newQuery(qstr);
SelectResults<?> result = (SelectResults<?>) query.execute((RegionFunctionContext) context);
ArrayList<?> arrayResult = (ArrayList<?>) result.asList();
context.getResultSender().sendResult(arrayResult);
context.getResultSender().lastResult(null);
} catch (Exception e) {
throw new FunctionException(e);
}
}
ClientCache cache;
Region<?, ?> individual;
cache = new ClientCacheFactory().set("name", "ClientWorker").set("cache-xml-file", "xml/clientCache.xml")
.create();
individual = cache.getRegion("Individual");
String qStr = "SELECT r1.id,r1.firstName, r1.lastName FROM /Individual r1";
try {
Object result = FunctionService.onRegion(individual)
.withArgs(qStr).execute("com.xxx.logic.MySelectPartitionFunction").getResult();
Output
[[struct(id:2,firstName:Basha,lastName:Shaik), struct(id:1,firstName:Krish,lastName:Chaitu), struct(id:5,firstName:Vigneshwaran,lastName:Ganesan)], null, [struct(id:4,firstName:Arun,lastName:Kishore), struct(id:3,firstName:Anurag,lastName:Kshirsagar)], null]

Update Query with annotation using Spring and MongoRepository

I am using the latest version of Spring Boot and Spring Data MongoRepository. I have written a custom repository interface
public interface CompanyRepository extends MongoRepository<Company, String>{
#Query(value = "{ 'employer.userId' : ?0 }")
Company findByCompanyUserUserId(String userId);
}
In the same way i want to use #Query annotation for updating a particular field. can someone suggest me?
Create an annotation like this:
#Documented
#Retention(RetentionPolicy.RUNTIME)
#Target({ElementType.METHOD})
public #interface MongoUpdate {
String find() default "{}";
String update() default "{}";
String collection();
boolean multi() default false;
}
And an aspect like this:
#Aspect
#Component
#SuppressWarnings("unchecked")
public class MongoUpdateAspect {
private static final Logger logger = LoggerFactory.getLogger(MongoUpdateAspect.class);
#Autowired
private MongoTemplate mongoTemplate;
#Pointcut("#annotation(com.ofb.commons.aop.common.MongoUpdate)")
public void pointCut() {
}
#Around("com.ofb.commons.aspect.MongoUpdateAspect.pointCut() && #annotation(mongoUpdate)")
public Object applyQueryUpdate(ProceedingJoinPoint joinPoint, MongoUpdate mongoUpdate) throws Throwable {
Object[] args = joinPoint.getArgs();
String findQuery = mongoUpdate.find();
String updateQuery = mongoUpdate.update();
String collection = mongoUpdate.collection();
boolean multiUpdate = mongoUpdate.multi();
for (int i = 0; i < args.length; i++) {
if (args[i] instanceof Collection) {
Collection collection1 = (Collection) args[i];
String replaceStr = (String) collection1.stream().map(object -> {
if (object instanceof Number) {
return object.toString();
} else {
return String.format("\"%s\"", object.toString());
}
}).collect(Collectors.joining(","));
findQuery = findQuery.replace(String.format("?%s", i), replaceStr);
updateQuery = updateQuery.replace(String.format("?%s", i), replaceStr);
} else if (args[i] instanceof Object[]) {
Object[] objects = (Object[]) args[i];
String replaceStr = Arrays.stream(objects).map(object -> {
if (object instanceof Number) {
return object.toString();
} else {
return String.format("\"%s\"", object.toString());
}
}).collect(Collectors.joining(","));
findQuery = findQuery.replace(String.format("?%s", i), replaceStr);
updateQuery = updateQuery.replace(String.format("?%s", i), replaceStr);
} else {
if (args[i] instanceof Number) {
findQuery = findQuery.replace(String.format("?%s", i), args[i].toString());
updateQuery.replace(String.format("?%s", i), args[i].toString());
} else {
findQuery = findQuery.replace(String.format("?%s", i), String.format("\"%s\"", args[i].toString()));
updateQuery =
updateQuery.replace(String.format("?%s", i), String.format("\"%s\"", args[i].toString()));
}
}
}
Query query = new BasicQuery(findQuery);
Update update = new BasicUpdate(updateQuery);
if (multiUpdate) {
mongoTemplate.updateMulti(query, update, collection);
} else {
mongoTemplate.updateFirst(query, update, collection);
}
return null;
}
}
This will not work in MongoRepository implemented interfaces but you can create an empty bodied method in your service layer
#MongoUpdate(find = {}, update = "{$push : {'offFeatures' : ?0}}", collection = "userPreference", multi = true)
public void offFeatures(String feature) {
}
It's a reasonable question. Assuming that you're using the org.springframework.data.mongodb.repository.MongoRepository class, can you not simply use the insert(..) or save(..) methods for what you need?
API docs

CQ5 multifield configuration service

I'm trying to create a CQ5 service with a multifield configuration interface. It would be something like this but at the click of PLUS button it would add not just a new row but a group of N rows.
Property
Field1 +-
Field2
....
FieldN
Any advice?
As far as I know there is no such possibility in the Apache Felix.
Depending on your actual requirement I would consider decomposing the configuration. Try moving all the fieldsets (groups of fields that you'd like to add through the plus button) into a separated configuration. So, closely to the slf4j.Logger configuration you would have a Configuration Factory approach.
A simple configuration factory can look like following
#Component(immediate = true, configurationFactory = true, metatype = true, policy = ConfigurationPolicy.OPTIONAL, name = "com.foo.bar.MyConfigurationProvider", label = "Multiple Configuration Provider")
#Service(serviceFactory = false, value = { MyConfigurationProvider.class })
#Properties({
#Property(name = "propertyA", label = "Value for property A"),
#Property(name = "propertyB", label = "Value for property B") })
public class MyConfigurationProvider {
private String propertyA;
private String propertyB;
#Activate
protected void activate(final Map<String, Object> properties, final ComponentContext componentContext) {
propertyA = PropertiesUtil.toStringArray(properties.get("propertyA"), defaultValue);
propertyB = PropertiesUtil.toStringArray(properties.get("propertyB"), defaultValue);
}
}
Using it is as simple as adding a reference in any #Component
#Reference(cardinality = ReferenceCardinality.OPTIONAL_MULTIPLE, referenceInterface = MyConfigurationProvider.class, policy = ReferencePolicy.DYNAMIC)
private final List<MyConfigurationProvider> providers = new LinkedList<MyConfigurationProvider>();
protected void bindProviders(MyConfigurationProvider provider) {
providers.add(provider);
}
protected void unbindProviders(MyConfigurationProvider provider) {
providers.remove(provider);
}
This is one way of doing it.
#Component(label = "My Service", metatype = true, immediate = true)
#Service(MyService.class)
#Properties({
#Property(name = "my.property", description = "Provide details Eg: url=http://www.google.com|size=10|path=/content/project", value = "", unbounded = PropertyUnbounded.ARRAY) })
public class MyService {
private String[] myPropertyDetails;
#Activate
protected void activate(ComponentContext ctx) {
this.myPropertyDetails = getPropertyAsArray(ctx.getProperties().get("my.property"));
try {
if (null != myPropertyDetails && myPropertyDetails.length > 0) {
for(String myPropertyDetail : myPropertyDetails) {
Map<String, String> map = new HashMap<String, String>();
String[] propertyDetails = myPropertyDetails.split("|");
for (String keyValuePair : propertyDetails) {
String[] keyValue = keyValuePair.split("=");
if (null != keyValue && keyValue.length > 1) {
map.put(keyValue[0], keyValue[1]);
}
}
/* the map now has all the properties in the form of key value pairs for single field
use this for logic execution. when there are no multiple properties in the row,
you can skip the logic to split and add in the map */
}
}
} catch (Exception e) {
log.error( "Exception ", e.getMessage());
}
}
private String[] getPropertyAsArray(Object obj) {
String[] paths = { "" };
if (obj != null) {
if (obj instanceof String[]) {
paths = (String[]) obj;
} else {
paths = new String[1];
paths[0] = (String) obj;
}
}
return paths;
}
}

Testing Intuit IPP

I would like to create some unit tests for inserting data to QuickBooks Online. I am having a problem with the authentication step:
public DataServices Authenticate(IntuitServicesType intuitDataServicesType)
{
DataServices dataServices = null;
string accessToken = HttpContext.Current.Session["accessToken"].ToString();
string accessTokenSecret = HttpContext.Current.Session["accessTokenSecret"].ToString();
string companyID = HttpContext.Current.Session["realm"].ToString();
// now auth to IA
OAuthRequestValidator oauthValidator = new OAuthRequestValidator(accessToken, accessTokenSecret, ConfigurationManager.AppSettings["consumerKey"].ToString(), ConfigurationManager.AppSettings["consumerSecret"].ToString());
ServiceContext context = new ServiceContext(oauthValidator, accessToken, companyID, intuitDataServicesType);
dataServices = new DataServices(context);
if (HttpContext.Current != null && HttpContext.Current.Session != null)
{
HttpContext.Current.Session["DataServices"] = dataServices;
}
return dataServices;
}
In my unit test project, which has no user interface, how can I obtain an access token and an access token secret? I cannot log into Intuit from that area.
[TestMethod()]
public void AuthorizeWithHeadersTest()
{
string accessToken = ConfigurationManager.AppSettings["AccessTokenQBD"];
string accessTokenSecret = ConfigurationManager.AppSettings["AccessTokenSecretQBD"];
string consumerKey = ConfigurationManager.AppSettings["ConsumerKeyQBD"];
string consumerKeySecret = ConfigurationManager.AppSettings["ConsumerSecretQBD"];
string requestUri = "https://appcenter.intuit.com/Developer/Create";
WebRequest webRequest = WebRequest.Create(requestUri);
webRequest.Headers.Add("ContentType", "text/xml");
OAuthRequestValidator target = new OAuthRequestValidator(accessToken, accessTokenSecret, consumerKey, consumerKeySecret);
target.Authorize(webRequest, string.Empty);
Assert.IsTrue(webRequest.Headers.Count > 0);
}
I'm sharing a sample standalone java code snippet. You can try the same in .net
From appcenter, you can create an app to get consumer key, consumer secret and app token.
Using apiexplorer and the above consumer key, consumer secret, you can get access tokens.
AppCenter - https://appcenter.intuit.com/
Apiexplorer - https://developer.intuit.com/apiexplorer?apiname=V2QBO
You can set all the 5 values in the standalone program(setupQBO method). It will work fine.
import java.util.ArrayList;
import java.util.List;
import com.intuit.ds.qb.PartyType;
import com.intuit.ds.qb.QBCustomer;
import com.intuit.ds.qb.QBCustomerService;
import com.intuit.ds.qb.QBInvalidContextException;
import com.intuit.ds.qb.QBObjectFactory;
import com.intuit.ds.qb.QBServiceFactory;
import com.intuit.platform.client.PlatformSessionContext;
import com.intuit.platform.client.PlatformServiceType;
import com.intuit.platform.client.security.OAuthCredentials;
import org.slf4j.Logger;
// QBO API Docs - https://developer.intuit.com/docs/0025_quickbooksapi/0050_data_services/v2/0400_quickbooks_online/Customer
// JavaDocs - http://developer-static.intuit.com/SDKDocs/QBV2Doc/ipp-java-devkit-2.0.10-SNAPSHOT-javadoc/
public class CodegenStubCustomerall {
static String accesstoken = "";
static String accessstokensecret = "";
static String appToken = "";
static String oauth_consumer_key = "";
static String oauth_consumer_secret = "";
static String realmID = "";
static String dataSource = "";
final PlatformSessionContext context;
public CodegenStubCustomerall(PlatformSessionContext context) {
this.context = context;
}
public void testAdd(){
try {
QBCustomer entityPojo = QBObjectFactory.getQBObject(context, QBCustomer.class);
entityPojo.setName("TestQBCustomer12345");
entityPojo.setTypeOf(PartyType.PERSON);
QBCustomerService service = QBServiceFactory.getService(context, QBCustomerService.class);
QBCustomer qbQBCustomer = service.addCustomer(context, entityPojo);
} catch (QBInvalidContextException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public List<QBCustomer> testGetAll() {
final List<QBCustomer> entityList = new ArrayList<QBCustomer>();
try {
QBCustomerService service = QBServiceFactory.getService(context, QBCustomerService.class);
List<QBCustomer> qbCustomerList = service.findAll(context, 1,100);
for (QBCustomer each : qbCustomerList) {
entityList.add(each);
}
} catch (QBInvalidContextException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return entityList;
}
public static void main(String args[]) {
PlatformSessionContext context = getPlatformContext("QBO");
CodegenStubCustomerall testObj = new CodegenStubCustomerall(context);
testObj.testGetAll();
}
public static PlatformSessionContext getPlatformContext(String dataSource) {
PlatformServiceType serviceType = null;
if (dataSource.equalsIgnoreCase("QBO")) {
serviceType = PlatformServiceType.QBO;
setupQBO();
}
final OAuthCredentials oauthcredentials = new OAuthCredentials(
oauth_consumer_key, oauth_consumer_secret, accesstoken,
accessstokensecret);
final PlatformSessionContext context = new PlatformSessionContext(
oauthcredentials, appToken, serviceType, realmID);
return context;
}
private static void setupQBO() {
System.out.println("QBO token setup");
accesstoken = "replace your tokens";
accessstokensecret = "replace your tokens";
appToken = "replace your tokens";
oauth_consumer_key = "replace your tokens";
oauth_consumer_secret = "replace your tokens";
realmID = "7123456720";
dataSource = "QBO";
}
}
For sample .net code, you can refer this link.
https://developer.intuit.com/docs/0025_quickbooksapi/0055_devkits/0100_ipp_.net_devkit/0299_synchronous_calls/0001_data_service_apis
Thanks

How can we solve An entity with the same identity already exists in this EntitySet

public BusinessAccounting.ViewModel.Account.AccountViewModel AccountVM;
public QBImportDataWizard()
{
InitializeComponent();
dcBusinessAccountingContext.Load(dcBusinessAccountingContext.GetAccountsQuery());
}
void oQB_RetrieveQBAccountsCompleted(object sender, QBAccountsServiceReference.RetrieveQBAccountsCompletedEventArgs e)
{
foreach (BusinessAccounting.QBAccountsServiceReference.QBAccounts acc in QBAccountlist)
{
AccountVM.CurrentAccount.Active = acc.Active;
AccountVM.CurrentAccount.Hierarchy =null;
AccountVM.CurrentAccount.HierarchyLevel = acc.Sublevel;
AccountVM.CurrentAccount.CashFlowID = 3;
AccountVM.CurrentAccount.OpeningBalance = null;
AccountVM.CurrentAccount.OpeningBalanceDate = DateTime.Now;
AccountVM.CurrentAccount.Category1099ID = null;
AccountVM.CurrentAccount.Remarks ="";
AccountVM.CurrentAccount.BankID = 0;//Here i am getting error.
}
}
If I remove below line under QBImportDataWizard() dcBusinessAccountingContext.Load(dcBusinessAccountingContext.GetAccountsQuery()); then it is not giving any error. Let me know why?