Not able to insert data into solr4.3 using this java code - java

My java code looks something like this:
public class CreateSolr4Doc {
public static void main(String[] args) {
int recordCount = 3;
CreateSolr4Doc instance = new CreateSolr4Doc();
instance.createDummyData(recordCount);
}
private void createDummyData(int recordCount) {
String url = "http://localhost:8983/solr/collection1";
System.out.println(url);
HttpSolrServer solr = new HttpSolrServer(url);
for (int index = 0; index < recordCount; index++) {
for(int j=1;j<=20000;j++)
{
SolrInputDocument doc = new SolrInputDocument();
Date date = new Date();
doc.addField("id","ibsfdjkhfb"+index+j);
doc.addField("mongoid", "4eebb9db43d7391c16509153");
doc.addField("agency","AFP");
doc.addField("title","Masked men loot cash, cellphones"+(index+1));
doc.addField("story",(index+1) + "PATNA: Giving a damn to");
doc.addField("mimetype","TEXT");
doc.addField("subject","The criminals first reached the office-cum")
doc.addField("coverage","patna");
doc.addField("isSyndicated",1);
doc.addField("createdDate",org.apache.commons.lang.time.DateUtils.addDays(date, -(index+101)));
doc.addField("expiryDate","2061-12-17T03:06:13Z");
doc.addField("language","en");
doc.addField("version","1.0");
doc.addField("ingestionDate","2011-12-16T21:36:28.296Z");
doc.addField("ingestionDate_index","2011-12-17T03:06:00Z");
System.out.println("Inserting document"+" "+(j)+" "+(index+1));
try {
solr.add(doc);
} catch (SolrServerException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
UpdateResponse response = solr.commit();
System.out.println(response);
} catch (SolrServerException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
When I insert data I get an error message something like this:-
Inserting document 1 1
Exception in thread "main" org.apache.solr.common.SolrException: ERROR: [doc=ibsfdjkhfb01] unknown field 'mongoid'
The error is encountered when i add fields in the document.
I don't know how to proceed.

Based on the error message, it appears that you have a field that is not in your schema. Try adding mongoid to your schema.xml and see if that helps.

Related

How to extract try catch outside method?

I have this method sendParameterValueAsMQTTMessage() which I use to publish message via MQTT on a specific topic. I am using try catch two times after another (not nested) but it still seems somewhat ugly and overcrowding the method. I read an article on clean code where Uncle Bob talks about extracting the body of try catch but I seem to not grasp it quite well or at least not in my case.
How could I get rid of the try catch in my method by extracting it outside?
public void sendParameterValueAsMQTTMessage() {
String payload = null;
try {
payload = convertToJSONString("range", String.valueOf(range));
} catch (JSONException e) {
this.logger.log(Level.ERROR, e);
}
MQTTMessage message = new MQTTMessage(MQTTTopics.RANGE_TOPIC,payload,0);
try {
this.client.publish(message);
Thread.sleep(3000);
} catch (Exception e) {
this.logger.log(Level.ERROR, e);
}
}
there are multiple different problems with provided code, here is how I'd refactor it:
public void sendParameterValueAsMQTTMessage() {
final String payload = tryGetPayloadAsJson();
if (payload != null) {
trySendPayloadViaMQTT(payload);
}
}
private String tryGetPayloadAsJson() {
try {
return convertToJSONString("range", String.valueOf(range));
} catch (JSONException e) {
this.logger.log(Level.ERROR, e);
}
return null;
}
private void trySendPayloadViaMQTT(final String payload) {
try {
final MQTTMessage message = new MQTTMessage(MQTTTopics.RANGE_TOPIC, payload, 0);
this.client.publish(message);
Thread.sleep(3000);
} catch (Exception e) {
this.logger.log(Level.ERROR, e);
}
}
one thing which might be improved here based on Uncle Bob's advice is to actually move try/catch outside of trySendPayloadViaMQTT, like this:
public void sendParameterValueAsMQTTMessage() {
final String payload = tryGetPayloadAsJson();
if (payload != null) {
trySendPayloadViaMQTT(payload);
}
}
private String tryGetPayloadAsJson() {
try {
return convertToJSONString("range", String.valueOf(range));
} catch (JSONException e) {
this.logger.log(Level.ERROR, e);
}
return null;
}
private void trySendPayloadViaMQTT(final String payload) {
try {
sendPayloadViaMQTT(payload);
} catch (Exception e) {
this.logger.log(Level.ERROR, e);
}
}
private void sendPayloadViaMQTT(final String payload) {
final MQTTMessage message = new MQTTMessage(MQTTTopics.RANGE_TOPIC, payload, 0);
this.client.publish(message);
Thread.sleep(3000);
}
you can put all of your code in just one try block and set multiple catches, when ever an exception be happened, the catch that is revelated to it will be execute, like:
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
You can use single general catch for both possible exceptions inside the method as following:
public void sendParameterValueAsMQTTMessage() {
String payload = null;
try {
payload = convertToJSONString("range", String.valueOf(range));
MQTTMessage message = new MQTTMessage(MQTTTopics.RANGE_TOPIC,payload,0);
this.client.publish(message);
Thread.sleep(3000);
} catch (Exception e) {
this.logger.log(Level.ERROR, e);
}
}
public void sendParameterValueAsMQTTMessage() {
String payload = null;
try {
payload = convertToJSONString("range", String.valueOf(range));
} catch (JSONException e) {
this.logger.log(Level.ERROR, e);
}
MQTTMessage message = new MQTTMessage(MQTTTopics.RANGE_TOPIC,payload,0);
publishMessage(message); //extracted in a new method
}
public void publishMessage(MQTTMessage message){
try {
this.client.publish(message);
Thread.sleep(3000);
} catch (Exception e) {
this.logger.log(Level.ERROR, e);
}
}

How do I save the id from chatid with the telegram api

Hello. I'm trying to solve this problem for a while now. For some
reason I keep getting null pointer exception when I try to save a
object in my repository. Below you can see what happens and my
functions.
java.lang.NullPointerException at com.br.einstein.api.service.ApiTelegram.sendMsg(ApiTelegram.java:104)
at
com.br.einstein.api.service.ApiTelegram.onUpdateReceived(ApiTelegram.java:81)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1541) at
org.telegram.telegrambots.meta.generics.LongPollingBot.onUpdatesReceived(LongPollingBot.java:27)
at
org.telegram.telegrambots.updatesreceivers.DefaultBotSession$HandlerThread.run(DefaultBotSession.java:317)
public void onUpdateReceived(Update update) {
ApiEinstein api = new ApiEinstein();
try {
JsonObject objSession = api.getSessionDetails();
String message = update.getMessage().getText();
api.sendChatRequest(objSession);
List < String > list = new ApiEinstein().ReadChatDetails(objSession);
sendMsg(update.getMessage().getChatId().toString(), list.toString());
new ApiEinstein().SendChatMessage(objSession, message);
api.syncChatSession(objSession);
} catch (Exception e) {
e.printStackTrace();
}
}
public synchronized void sendMsg(String chatId, String s) {
SendMessage sendMessage = new SendMessage();
// sendMessage.enableMarkdown(true);
sendMessage.setChatId(chatId);
sendMessage.setText(s);
long id = Long.valueOf(chatId);
Telegram telegram = new Telegram();
telegram.setChatId(id);
repository.save(telegram);
try {
execute(sendMessage);
} catch (TelegramApiException e) {
e.printStackTrace();
}
} ```

Read multiple different objects in a text file - Java

I'm working on a school project which consist in creating race-tournaments
I'm having an issue right now because I have multiple races-type (CarRace/BikeRace) which have Race as a parent
I'm saving an array of races no matter the specific type.
And now I need to load this list of races
public static ArrayList<Course> loadLRace(String name) {
File inFile = new File(name+".txt");
FileInputStream inFileStream;
ArrayList<Race> lRace = new ArrayList<Race>();
try {
inFileStream = new FileInputStream(inFile);
ObjectInputStream inObjectStream = new ObjectInputStream(inFileStream);
int length = inObjectStream.readInt();
for(int i = 0; i < length; i++) {
Race race = (Race)inObjectStream.readObject();
lRace.add(Race);
}
inObjectStream.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
return lRace;
}
And I'm having a "non valid constructor" error, I guess this is because I don't deal with CarRace AND BikeRace separately, but how can I ?

How to retry particular piece of code in try block if any exceptions are happening?

I need to parse my HTML table coming from an URL using JSOUP and everything is working fine as of now. Now I want to add a retry mechanism if I see any exception. Below is my code -
public void collectMetrics() {
try {
URL url = new URL("some_url");
Document doc = Jsoup.parse(url, 9000);
for (Map.Entry<String, String> entry : mappings.entrySet()) {
calculateDiskFree(doc, entry.getValue(), entry.getKey());
}
// if it comes here, then it means everything is done successfully
// so no retry has to happen now
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
If there are any exceptions happening in the catch block, I would like to retry executing everything I have in my try block for n number of times. Is it possible to do?
You can put it in a loop.
boolean successful = false;
while (!successful) {
try {
URL url = new URL("some_url");
Document doc = Jsoup.parse(url, 9000);
for (Map.Entry<String, String> entry : mappings.entrySet()) {
calculateDiskFree(doc, entry.getValue(), entry.getKey());
}
successful = true;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
but you might then want to think about what happens if it just keeps failing.
If you only want to retry some specific number of times you can use a for loop.
for (int retries = 0; retries < 3; ++retries) {
try {
URL url = new URL("some_url");
Document doc = Jsoup.parse(url, 9000);
for (Map.Entry<String, String> entry : mappings.entrySet()) {
calculateDiskFree(doc, entry.getValue(), entry.getKey());
}
break;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Wrap the try block in an infinite loop and add return; after your work code:
public void collectMetrics() {
for (;;) {
try {
URL url = new URL("some_url");
Document doc = Jsoup.parse(url, 9000);
for (Map.Entry<String, String> entry : mappings.entrySet()) {
calculateDiskFree(doc, entry.getValue(), entry.getKey());
}
return;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
If you want to limit the number of tries (recommended), fill out the for loop, ie instead of for (;;), use:
for (int i = 0; i < 10; i++) { // try max 10 times
Create a while statement around the try catch statement then set up something to tell the while loop to stop repeating.

android - how to parse json from file in SDCard

hi i want to parse my downloaded json file that stored in the SDCard directory ,
i don't know how can i do that !
im google a lot but i can only find somethings like : BuffredReader , InputFileStream , ...
please help me !
here is part of my code but it have the problem i attached in the image :
File GroupsJsonFileAdress = new File(Enviroments.getExternalStorageDirectory() + "FOLDER/G.json");
try {
ObjectInputStream groupsInJson = new ObjectInputStream(new FileInputStream(GroupsJsonFileAdress));
JSONObject jsonObject = (JSONObject)groupsInJson.readObject();
String DATABASE_VERSION = jsonObject.getString("DBVersion");
JSONArray groupsArray = jsonObject.getJSONArray("Groups");
for (int i = 0; i < groupsArray.length(); i++) {
JSONObject groupJsonObjectReader = groupsArray.getJSONObject(i);
int id= groupJsonObjectReader.getInt("Id");
String gTitle = groupJsonObjectReader.getString("title");
Group loaderG = new Group();
loaderG.GroupId = id;
loaderG.Title = gTitle;
Log.i("INFO", loaderG.Title);
groupsClasses.add(loaderG);
}
} catch (StreamCorruptedException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
and here is the error i got :
http://i.stack.imgur.com/lQ3YN.jpg
Create a model that matches your Json architecture and then parse it using GSON librarie ;)
Easiest way to do it so far for me :)

Categories

Resources