Is there a way to artificially change the status of an exception from checked to unchecked?
For example, JSONException
is unchecked in Java SE but it is checked in Android Studio. So when porting a project, that makes frequent use of JSON-related methods, from IntelliJ IDEA (or any other Java SE IDE) to Android Studio, you have to manually try/catch
every single such call or choose to throw them in method signature and catch them elsewhere.
This process is extremely boring, mostly pointless, and as far as I know unavoidable. It is boring because you have to change a lot of already-working code and again change it back (or leave it redundantly) when you want to work on it again in SE, it is mostly pointless because some methods like calling put(key, value)
ona newly-created empty JSONObject
are obviously safe but you have to try/catch
them anyway, and it is unavoidable because Android Studio does not allow you to use another version of the org.json
library in your gradle.build
file.
My question is, how can we artificially change the status of such annoying exceptions so that both the compiler and the IDE do not expect us to catch them when mostly there is nothing to catch.
Thanks in advance.
do you know?
how many words do you know
See also questions close to this topic
-
Read each name in Array list to create seperate object for
I have a file that has student names, age, and an id number. I have a student class that holds the everything above for each student object. I stored all the names, id numbers. and age separately in an array list. Now im trying to assign the info to create a student object.
public class Student { private String lName; private int idNumber; private int age; public Student() { lName = ""; idNumber = 0; age = 0; } public Student(String l, int i, int a) { lName = l; idNumber = i; age = a; } public void setName(String last) { lName = last; } public String getName() { return lName; } public void setIdNum(int num) { idNumber = num; } public int getIdNum() { return idNumber; } public void setAge(int a) { age = a; } public int getAge() { return age; } }
My Text File looks something like this: This info is stored in parallel array lists. I don't quite get how to implement this into an object to pass it into my second contractor method.
Josh 2134 19 Smith 5256 21 Rogers 9248 19 Andrew 7742 20
Here's what I've tried;
public static void main(String[] args) { String file = "studentData.txt"; Scanner reader = new Scanner(file); ArrayList<String> lastNames = lNames(file); ArrayList<Integer> idNumbers = idNum(file); ArrayList<Integer> ageList = ages(file); Scanner input = new Scanner(System.in); Student s1 = new Student(); // confused about how to implement this constructor with the textile info for (int i = 0; i<idNumbers.size(); i++) { Student user = new Student(lastNames.get(i), idNumbers.get(i), ageList.get(i)); } //user enters idNumber to display age System.out.println("Enter ID Number"); //exception handling to be added int idNum = input.nextInt(); for (int i = 0; i<idNumbers.size(); i++) { if (idNum == idNumbers.get(i)) { s1.setAge(ageList.get(i)); System.out.println(s1.getAge()); } } }
-
Using EdittextPreference for Goto search
sorry for my poor English. I want to use EditTextPreference in my bottom nav like the pic below, ![screenshot][1]
I have recycleview xml in my project with in many sub cardview layouts(which is scrollable) and I want to create item in the bottom nav which is called "Goto". When the "Goto" item is clicked i want it to pop-up like the screenshot. And when user enters a number(according to the cardviews i.e if the number of cardview is 40 user must enter 1-40) I want to search the cardview by its ID. Thank you and I hope u got it, If u have any questions let me know [1]: https://i.stack.imgur.com/grK8P.jpg
My xml format look like this. As you see in the blow since the cardviews are huge in number it is not cool to scroll all the way down that is why i need Goto item in the bottom nav to search it by its ID when the user click number in the EditTextPreference as u see in the screenshot. i.e The screenshot is not from my app
<LinearLayout> <LinearLayout> <androidx.cardview.widget.CardView> <RealtiveLayout> <Textview/> <RealtiveLayout> </androidx.cardview.widget.CardView> </LinearLayout> <LinearLayout> <androidx.cardview.widget.CardView> <RealtiveLayout> <Textview/> <RealtiveLayout> </androidx.cardview.widget.CardView> </LinearLayout> <LinearLayout> <androidx.cardview.widget.CardView> <RealtiveLayout> <Textview/> <RealtiveLayout> </androidx.cardview.widget.CardView> </LinearLayout> <LinearLayout> <androidx.cardview.widget.CardView> <RealtiveLayout> <Textview/> <RealtiveLayout> </androidx.cardview.widget.CardView> </LinearLayout> .. .. .. .. many more..
-
How to get remaining time of the day in java?
I would like to calculate the time remaining for next day 00:00:00 from the current date time.
For e.g. time difference between 2
022-05-07T05:49:41.883807900Z
and2022-05-08T00:00:00Z
Expected answer:
18:10:19
or 65419 (in seconds).How can I achieve this with efficiently using java 8?
-
different between call view by name or use binding in android
i'am a newest in android kotlin
I want to know what is the difference between the two lines of code below and which one is better to use
class MainActivity : AppCompatActivity() { private lateinit var binding: ActivityMaindinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) bindins = DataBindingutil.setContentview( this, R.layout.activity_main) textview.text="text"//or binding.textview.text="text" }}
-
Get multiple times current time on single Button
I have a button showing text START when I click on it I shows me current time in textview.(I consider this time as start time). Than convert the text on Button into STOP. When I click on it again show me current time on another textview(I consider this time as stop time). And then calculate the difference between these two time. I want this same working for multiple time. I means First button show Text ENTER. When I click on it it should show current time in textview.(I will consider this time as Enter time). Than convert the text on Button into START. When I click on it again show me current time on another textview(I will consider this time as start time). Than convert the text on Button into STOP. When I click on it again show me current time on another textview(I will consider this time as STOP time). And last Than convert the text on Button into EXIT. When I click on it again show me current time on another textview(I will consider this time as Exit time).
Here is my code:
btn_start.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (isStarted){ Calendar calendar = Calendar.getInstance(); SimpleDateFormat format = new SimpleDateFormat("hh:mm:ss aa"); String time = format.format(calendar.getTime()); tvend.setText(time); try { Date date1 = format.parse(tvend.getText().toString()); Date date2 = format.parse(tvstarttime.getText().toString()); long mills = date1.getTime() - date2.getTime(); Log.v("Data1", ""+date1.getTime()); Log.v("Data2", ""+date2.getTime()); int hours = (int) (mills/(1000 * 60 * 60)); int mins = (int) (mills % (1000*60*60)); String diff = hours + ":" + mins; diffence.setText(diff); } catch (ParseException e) { e.printStackTrace(); } btn_start.setText("START"); }else { Calendar calendar = Calendar.getInstance(); SimpleDateFormat format = new SimpleDateFormat("hh:mm:ss aa"); String time1 = format.format(calendar.getTime()); tvstarttime.setText(time1); btn_start.setText("STOP"); } isStarted = !isStarted; } });
-
android emulator disable microphone when launching device
How do we disable the (virtual) microphone when launching the emulator?
Situation
When launching an Android Studio stock emulator device, the microphone is always enabled and listening.Why would we want this fix
- Convenience, Many users have a microphone headset and when the microphone is enabled, they lose noise canceling and/or stereo. It can be extremely annoying, forcing the user to disconnect the device which swaps the emulator audio + sounds to another microphone/speaker input/output.
- Security risk, the microphone is actively listening. Is the data going anywhere? Who knows...this is an unnecessary security risk for any organization, IE a dev is on a (zoom, teams, meetings) call with an open emulator that is using the microphone and listening).
Possible Solutions (based on practicality)
- flag to disable virtual audio devices (IE the mac's speaker or attached headphones w/ a microphone). I've seen 0 documentation regarding a flag like this.
- flag to provide to the emulator to disable all audio input (see answer 1). TLDR add the flag
-no-audio
- route the android studio emulator (or the mac's microphone audio input) to a virtual device that is not listening. Or have the default OS microphone input set to 0 volume. This can be done via macOSX Automator
- route the adb emulator to the mac's internal microphone instead of the current microphone to avoid it triggering the headsets microphone settings.
The preferred solution
- Microphone audio-in is disabled when booting the emulator
- Android device audio-out remains and uses the computer's default speakers
- The computer's default microphone is not triggered (at all) to avoid causing a stereo -> mono swap or noise cancellation breakage.
System Information:
- android emulator: 31.2.10.0
- MacOS 12.3.1
- Headsets tested with these issues:
- Bose NC 700
- Bose QC series
- Sony WF-1000XM4
- Sony WH-1000XM3
- any headset with a microphone connection macro that does something with the speaker (like talk through) or with the input audio like stereo -> mono.
-
functions running in loops and try/except does not work
I am a beginner in Python3 and was learning the basics during the last few weeks. I decided to use my knowledge and was trying to build a text-based game based on this example.
The first 3 scenes are similar to the ones from the example but I changed the story (can be ignored) and some other small things and also added two more scenes.
Description of game: In scene 1 the character wakes up in his room and needs to decide to leave or to stay in the room. Staying in the room will end the game. Leaving the room will initiate scene 2. In scene, 2 the character needs to make the choice to talk to a rabbit or ignore it. If he picks up the rabbit and talks to it the character will get a letter with a spell + a number (2). When he ignores the rabbit he won't have that information.
In scene 3 he will be attacked by a monster. he will die when he ignored the rabbit at the prior stage. He will win and proceed based on the other decision and will get the second number (3)
In scene 4 he needs to win a dance battle. If he leaves without trying the game is over. if he wins he gets the last number (1)
In scene 5 he can type in the three numbers in the order he was collecting them. if he is successful he wins.
Description of code: I started with a class (not finished that part) that should entail all necessary variables and functions. There is also an empty list that will be filled with the numbers during the course of the story.
At the end I want to use the try and except methods to catch errors in case the input is not an integer.
Issues: Scene 1 and 4 are working. Scene 2 and 3 are running in loops. not sure why since I copied those parts from the lin above. I only applied small changes to the code. Scene 5 works fine till
"Enter the second Number"
. It stops after submitting the input. I was changing already a few things but can't resolve my issues.Here is the code:
class Adventure_Text_Game (): def __init__(self): # check first part asdads # not ready import time numbers = [] # empty list that needs to be filled with numbers. those numbers will need to be entered to open the lock to rescue the parents # numbers that can be collected in story num1 = 2 num2 = 3 num3 = 1 #works fine def scene1(self): print("""\nWELCOME TO THE ADVENTURE GAME! Michael had a bad night and woke up in the middle of the night in his bedroom disturbed by an odd noise outside of the house. Should he stay stay in his room or take a look? Type your choice: Stay or Take a look?""") sc1 = input() time.sleep(2) while sc1 != "STAY" and sc1 != "TAKE A LOOK": #the conditon that keeps the loop running ans=='incorrect' if sc1.upper()=="STAY": print("\nMichael is a coward and is not leaving his room...Game Over") break elif sc1.upper()=="TAKE A LOOK": print("\nMichael takes all his courage and exits the room silently directly going to the garden where the noise came from.") scene2() else: print("ENTER THE CORRECT CHOICE! Stay or Take a Look?") sc1 = input() #caught in loop...why? def scene2(): print(""" Outside he finds a cute white little rabbit that has never been there before and also seems to be a little nervous. The neighbors also don't posess a rabit Should Michael pick up the rabbit or ignore him? Type your choice: Pick or Ignore? """) time.sleep(2) sc1 = input() while sc1 != "PICK" and sc1 != "IGNORE": if sc1.upper()=="PICK": print("""\nMichael but Michael sees a little tag that says "My name is Roger". Michael starts talking to the rabit and pets him to calm him down. Suddenly the rabbit starts talking and is telling Michael his parents are in danger captured by a monster only he knows how to defeat.""") time.sleep(2) print("The rabbit gave Michael a letter with a magical spell and a wooden wand which will help him to defeat the monster. Michael also sees the number", str(num1), "at the bottom of the page! The rabbit then hops away and disappeaed in the darkness. There was nothing else in the garden so he decided to walk towards the street.") pick="True" numbers.append(num1) print (numbers) elif sc1.upper()=='IGNORE': print("""\nMichael decided not to pick up the rabbit. There was nothing else in the garden so he decided to walk towards the street.""") pick="False" else: print("ENTER THE CORRECT CHOICE! Stay or Evaluate?") sc1 = input() scene3(pick) #caught in loop....why? def scene3(pick): print("""\n\nWhen arriving at the pedestrian way of his street, Michael saw the MONSTER in front of him! It had red eyes and evil looks. He got very scared! """) time.sleep(2) if(pick=="True"): time.sleep(2) print("""But then he remembered! He had that letter and that wand from the rabbit. Well she had nothing to lose!""") time.sleep(2) print("\nHe starts reading the spell while holding the wand. The wand created a bright light followed by an explosion which vaporized the monster. On the ground Michael saw only a heap of ashes in the form of another number - the number", str(num2)) numbers.append(num2) print (numbers) elif(pick=="False"): print("The monster attacked Michael and hurt him badly....Game over!") time.sleep(2) scene4() #works fine def scene4(): print ("""\nMichael now sees a little light coming from a house across the street. So many strange things already happened which is why he approcahed the house carefully. He arrived at the window and saw a dancing Leprachaun.""") time.sleep(2) print ("""\nThe Leprachaun was expecting Michael already and insisted to have a step dance battle in order to get passed him.""") time.sleep(2) print ("""Type your choice: Dance or Leave?""") sc1 = input() time.sleep(2) while sc1 != "DANCE" and sc1 != "LEAVE": if sc1.upper()=="LEAVE": print("\nYou didn't rescue your parents...Game Over") break elif sc1.upper()=="DANCE": print ("""\nAfter all what happended that night he didn't really question it and started moving his feet although had no clue how to dance at all But to his and the Leprachaun's surprise he danced like he was born stepdancer. His legs were basically flying. The Leprachaun couldn't believe what he saw and could only forfeit.""") time.sleep(2) print ("Before the Leprachaun disappeared he gave Michael another number - number", str(num3)) numbers.append(num3) scene5() else: print("ENTER THE CORRECT CHOICE! Dance or Leave?") sc1 = input() #need to check exception def scene5(): print ("""\nMichael is now able to get passed the Leprachaun and is now standing in front of a door that is locked. Next to the door he finds a keypad. He figures that he needs to type in the three digits he was collecting earlier.""") sc1 = input("Enter the first number") sc1 = int(sc1) try: if sc1 == numbers [0]: print ("This number is correct!") sc1 = input("Enter the second number") if sc1 == numbers [1]: print ("This number is correct!") sc1 = input("Enter the third number") if sc1 == numbers [2]: print ("Congratulations! You can open the door and rescue your parents! ") except (ValueError, TypeError): #type error in case number is not an integer print("Please enter a proper number")
-
Two indexes library a search success a failure
java.lang.RuntimeException: ElasticsearchStatusException[Elasticsearch exception [type=search_phase_execution_exception, reason=all shards failed]] at cn.itcast.dewu.service.impl.BlogServiceImpl.queryblogByContent(BlogServiceImpl.java:322) ~[classes/:na] at cn.itcast.dewu.service.impl.BlogServiceImpl$$FastClassBySpringCGLIB$$1f6b53ac.invoke() ~[classes/:na] at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218) ~[spring-core-5.2.15.RELEASE.jar:5.2.15.RELEASE] at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:688) ~[spring-aop-5.2.15.RELEASE.jar:5.2.15.RELEASE] at cn.itcast.dewu.service.impl.BlogServiceImpl$$EnhancerBySpringCGLIB$$45d04fb3.queryblogByContent() ~[classes/:na] at cn.itcast.dewu.controller.BolgController.queryblogOrGoods(BolgController.java:113) ~[classes/:na] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_202] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_202] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_202] at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_202] at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190) ~[spring-web-5.2.15.RELEASE.jar:5.2.15.RELEASE] at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138) ~[spring-web-5.2.15.RELEASE.jar:5.2.15.RELEASE] at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:105) ~[spring-webmvc-5.2.15.RELEASE.jar:5.2.15.RELEASE] at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:878) ~[spring-webmvc-5.2.15.RELEASE.jar:5.2.15.RELEASE] at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:792) ~[spring-webmvc-5.2.15.RELEASE.jar:5.2.15.RELEASE] at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.2.15.RELEASE.jar:5.2.15.RELEASE] at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040) ~[spring-webmvc-5.2.15.RELEASE.jar:5.2.15.RELEASE] at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943) ~[spring-webmvc-5.2.15.RELEASE.jar:5.2.15.RELEASE] at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) [spring-webmvc-5.2.15.RELEASE.jar:5.2.15.RELEASE] at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898) [spring-webmvc-5.2.15.RELEASE.jar:5.2.15.RELEASE] at javax.servlet.http.HttpServlet.service(HttpServlet.java:626) [tomcat-embed-core-9.0.46.jar:4.0.FR] at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) [spring-webmvc-5.2.15.RELEASE.jar:5.2.15.RELEASE] at javax.servlet.http.HttpServlet.service(HttpServlet.java:733) [tomcat-embed-core-9.0.46.jar:4.0.FR] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227) [tomcat-embed-core-9.0.46.jar:9.0.46] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) [tomcat-embed-core-9.0.46.jar:9.0.46] at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) [tomcat-embed-websocket-9.0.46.jar:9.0.46] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) [tomcat-embed-core-9.0.46.jar:9.0.46] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) [tomcat-embed-core-9.0.46.jar:9.0.46] at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) [spring-web-5.2.15.RELEASE.jar:5.2.15.RELEASE] at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) [spring-web-5.2.15.RELEASE.jar:5.2.15.RELEASE] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) [tomcat-embed-core-9.0.46.jar:9.0.46] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) [tomcat-embed-core-9.0.46.jar:9.0.46] at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) [spring-web-5.2.15.RELEASE.jar:5.2.15.RELEASE] at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) [spring-web-5.2.15.RELEASE.jar:5.2.15.RELEASE] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) [tomcat-embed-core-9.0.46.jar:9.0.46] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) [tomcat-embed-core-9.0.46.jar:9.0.46] at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) [spring-web-5.2.15.RELEASE.jar:5.2.15.RELEASE] at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) [spring-web-5.2.15.RELEASE.jar:5.2.15.RELEASE] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) [tomcat-embed-core-9.0.46.jar:9.0.46] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) [tomcat-embed-core-9.0.46.jar:9.0.46] at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) [tomcat-embed-core-9.0.46.jar:9.0.46] at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97) [tomcat-embed-core-9.0.46.jar:9.0.46] at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542) [tomcat-embed-core-9.0.46.jar:9.0.46] at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:143) [tomcat-embed-core-9.0.46.jar:9.0.46] at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) [tomcat-embed-core-9.0.46.jar:9.0.46] at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78) [tomcat-embed-core-9.0.46.jar:9.0.46] at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357) [tomcat-embed-core-9.0.46.jar:9.0.46] at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:374) [tomcat-embed-core-9.0.46.jar:9.0.46] at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) [tomcat-embed-core-9.0.46.jar:9.0.46] at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:893) [tomcat-embed-core-9.0.46.jar:9.0.46] at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1707) [tomcat-embed-core-9.0.46.jar:9.0.46] at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-9.0.46.jar:9.0.46] at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [na:1.8.0_202] at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [na:1.8.0_202] at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-9.0.46.jar:9.0.46] at java.lang.Thread.run(Thread.java:748) [na:1.8.0_202] Caused by: org.elasticsearch.ElasticsearchStatusException: Elasticsearch exception [type=search_phase_execution_exception, reason=all shards failed] at org.elasticsearch.rest.BytesRestResponse.errorFromXContent(BytesRestResponse.java:176) ~[elasticsearch-7.12.1.jar:7.12.1] at org.elasticsearch.client.RestHighLevelClient.parseEntity(RestHighLevelClient.java:1933) ~[elasticsearch-rest-high-level-client-7.12.1.jar:7.12.1] at org.elasticsearch.client.RestHighLevelClient.parseResponseException(RestHighLevelClient.java:1910) ~[elasticsearch-rest-high-level-client-7.12.1.jar:7.12.1] at org.elasticsearch.client.RestHighLevelClient.internalPerformRequest(RestHighLevelClient.java:1667) ~[elasticsearch-rest-high-level-client-7.12.1.jar:7.12.1] at org.elasticsearch.client.RestHighLevelClient.performRequest(RestHighLevelClient.java:1624) ~[elasticsearch-rest-high-level-client-7.12.1.jar:7.12.1] at org.elasticsearch.client.RestHighLevelClient.performRequestAndParseEntity(RestHighLevelClient.java:1594) ~[elasticsearch-rest-high-level-client-7.12.1.jar:7.12.1] at org.elasticsearch.client.RestHighLevelClient.search(RestHighLevelClient.java:1110) ~[elasticsearch-rest-high-level-client-7.12.1.jar:7.12.1] at cn.itcast.dewu.service.impl.BlogServiceImpl.queryblogByContent(BlogServiceImpl.java:319) ~[classes/:na] ... 55 common frames omitted Suppressed: org.elasticsearch.client.ResponseException: method [POST], host [http://122.112.178.190:9200], URI [/blog_index/_search?typed_keys=true&max_concurrent_shard_requests=5&ignore_unavailable=false&expand_wildcards=open&allow_no_indices=true&ignore_throttled=true&search_type=query_then_fetch&batched_reduce_size=512&ccs_minimize_roundtrips=true], status line [HTTP/1.1 400 Bad Request] {"error":{"root_cause":[{"type":"query_shard_exception","reason":"failed to create query: class org.elasticsearch.index.fielddata.plain.SortedSetOrdinalsIndexFieldData cannot be cast to class org.elasticsearch.index.fielddata.IndexNumericFieldData (org.elasticsearch.index.fielddata.plain.SortedSetOrdinalsIndexFieldData and org.elasticsearch.index.fielddata.IndexNumericFieldData are in unnamed module of loader 'app')","index_uuid":"mQOmBb5rSJO5IuKFftlpyQ","index":"blog_index"}],"type":"search_phase_execution_exception","reason":"all shards failed","phase":"query","grouped":true,"failed_shards":[{"shard":0,"index":"blog_index","node":"ZNVNC5YPRqaIpz6k5nFsHA","reason":{"type":"query_shard_exception","reason":"failed to create query: class org.elasticsearch.index.fielddata.plain.SortedSetOrdinalsIndexFieldData cannot be cast to class org.elasticsearch.index.fielddata.IndexNumericFieldData (org.elasticsearch.index.fielddata.plain.SortedSetOrdinalsIndexFieldData and org.elasticsearch.index.fielddata.IndexNumericFieldData are in unnamed module of loader 'app')","index_uuid":"mQOmBb5rSJO5IuKFftlpyQ","index":"blog_index","caused_by":{"type":"class_cast_exception","reason":"class org.elasticsearch.index.fielddata.plain.SortedSetOrdinalsIndexFieldData cannot be cast to class org.elasticsearch.index.fielddata.IndexNumericFieldData (org.elasticsearch.index.fielddata.plain.SortedSetOrdinalsIndexFieldData and org.elasticsearch.index.fielddata.IndexNumericFieldData are in unnamed module of loader 'app')"}}}]},"status":400} at org.elasticsearch.client.RestClient.convertResponse(RestClient.java:326) ~[elasticsearch-rest-client-7.12.1.jar:7.12.1] at org.elasticsearch.client.RestClient.performRequest(RestClient.java:296) ~[elasticsearch-rest-client-7.12.1.jar:7.12.1] at org.elasticsearch.client.RestClient.performRequest(RestClient.java:270) ~[elasticsearch-rest-client-7.12.1.jar:7.12.1] at org.elasticsearch.client.RestHighLevelClient.internalPerformRequest(RestHighLevelClient.java:1654) ~[elasticsearch-rest-high-level-client-7.12.1.jar:7.12.1] ... 59 common frames omitted
-
Catching SyntaxError from ast.literal_eval
I have the following code to evaluate some configuration values stored in a file:
from ast import literal_eval for key, value in dict_read_from_file.items(): try: cfg[key] = literal_eval(value) except ValueError: cfg[key] = value
However, with certain inputs
literal_eval
raises aSyntaxError
, rather than aValueError
:>>> literal_eval('asdf') Traceback (most recent call last): [...] ValueError: malformed node or string on line 1: <ast.Name object at 0x000001A065B69AE0> >>> literal_eval('123 4') Traceback (most recent call last): [...] File "ast.py", line 50, in parse return compile(source, filename, mode, flags, File "<unknown>", line 1 123 4 ^ SyntaxError: invalid syntax
But Python doesn't seem to let me catch the
SyntaxError
:>>> try: ... literal_eval('123 4') ... except ValueError | SyntaxError: ... print("Fixing") ... Traceback (most recent call last): [...] SyntaxError: invalid syntax During handling of the above exception, another exception occurred: Traceback (most recent call last): File "<stdin>", line 3, in <module> TypeError: catching classes that do not inherit from BaseException is not allowed
How do I catch and properly handle this
SyntaxError
? -
Iterate and modify a JSONObject
I have a json blob as below:
{ "name": "ABC", "type": "School", "state": { "events" : [ { "event": "Session Start", "timestamp" : 1.6504826230744574E9, "name": "Session Start 2020", "venue" : "London" }, { "event": "Parents Meet", "timestamp" : 1.6504826230744574E9, "name": "Parents Meet 2020", "venue" : "London", "noOfAttendees" : 40 }, { "event": "Annual Fair", "timestamp" : 1.6504826230744574E9, "name": "Annual Fair 2020", "venue" : "London", "noOfvendors" : 10, "vendorDetails": { ... } }, { "event": "Session Start", "timestamp" : 1.6504826881501477E9, "name": "Session Start 2021", "venue" : "US" }, { "event": "Assembly", "timestamp" : 1.6504826881501477E9, "name": "Assembly 2021", "venue" : "US", "noOfAttendees" : 50 }, { "event": "Annual Fair", "timestamp" : 1.6504826881501477E9, "name": "Annual Fair 2021", "venue" : "US", "noOfvendors" : 20, "vendorDetails": { ... } } ], "group" : "A" } }
This is just an example for the purposes of posting here. In this example, we see that it provides a list of all events that happen for a school every year and the list is a cumulative one i.e. previous year events also get appended. What we know is every year's events will start with 'Session Start' event. I want to go through this object and end with just the latest bunch of events. Please ignore the timestamp or the year in the name of the events, they are just samples here and I don't have that sort of information in real world. The end result I need is :
{ "name": "ABC", "type": "School", "state": { "events" : [ { "event": "Session Start", "timestamp" : 1.6504826881501477E9, "name": "Session Start 2021", "venue" : "US" }, { "event": "Assembly", "timestamp" : 1.6504826881501477E9, "name": "Assembly 2021", "venue" : "US", "noOfAttendees" : 50 }, { "event": "Annual Fair", "timestamp" : 1.6504826881501477E9, "name": "Annual Fair 2021", "venue" : "US", "noOfvendors" : 20, "vendorDetails": { ... } } ], "group" : "A" } }
So, I want to keep the last set of events starting with the 'Session Start' event. I know for sure that there will be >=1 events in this with the name 'Session Start' and I want to keep only the events that follow that very last 'Session Start'.
I can iterate through this using JSONObject and JSONArray, but I'm not sure how to go about editing this object. Please note the name of the events can be different each year eg. due to Covid, we might not have an 'Annual Fair' in year 2022, etc.The only thing static is the 'Session Start' event that i need to grab from the bottom.
-
JSON and Java: I store a long. I want to get the long. But: "org.json.JSONException: JSONObject is not a long". What's wrong?
When I try to make the following (using org.json):
JSONObject jo = new JSONObject(); jo.append("theLong", 1l); Long theLong = jo.getLong("theLong");
I get the exception:
org.json.JSONException: JSONObject["theLong"] is not a long. [...] Caused by: java.lang.NumberFormatException: For input string: "[1]"
What am I doing wrong?
Remark: Also unnecessarily boxing the long in a long
jo.append("theLong", new Long(1l));
(to be sure that aLong
is passed, not along
) wont help. -
CSV to JSON in JAVA (org.json) Headers to keys not working
This is the content of my CSV File:
FID,OBJECTID,SHAPE,LAGE,GRILLPLATZ_ID,RESERVIERUNG,WEBLINK1,SE_ANNO_CAD_DAT "GRILLPLATZOGD.6748,6748,POINT (16.465255884594104 48.19018769574157),""22., Donauinsel, ca. 350 Meter stromab der Steinspornbrücke (Inselmitte, Erdwall)"",15,ja,http://www.wien.gv.at/amtshelfer/umwelt/wasserbau/donauinsel/grillplatzreservierung.html," "GRILLPLATZOGD.6749,6749,POINT (16.48177464603615 48.183356069714286),""22., Neue Donau, linkes Ufer, zwischen Steinspornbrücke und Waluliso Brücke (bei km 5,1) (Dammbereich) "",16,ja,http://www.wien.gv.at/amtshelfer/umwelt/wasserbau/donauinsel/grillplatzreservierung.html," "GRILLPLATZOGD.6750,6750,POINT (16.460158556964053 48.177745677669925),""11., Donaukanal, Alberner Hafenzufahrtsstraße, Nähe Margetinstraße"",0,nein,http://www.wien.gv.at/umwelt/wald/freizeit/grillen/," "GRILLPLATZOGD.6751,6751,POINT (16.22577870779843 48.20612009507929),""14., Auhof - Retentionsbecken"",0,nein,http://www.wien.gv.at/umwelt/wald/freizeit/grillen/,"
My program reads the file and then uses the org.json lib to produce a JSONArray filled with JSONObjects from the CSV.
The output of my program looks like this atm:
[{"FID":"GRILLPLATZOGD.6748,6748,POINT (16.465255884594104 48.19018769574157),\"22., Donauinsel, ca. 350 Meter stromab der Steinspornbrücke (Inselmitte, Erdwall)\",15,ja,http://www.wien.gv.at/amtshelfer/umwelt/wasserbau/donauinsel/grillplatzreservierung.html,"} and so on...
My problem is, that only the first part of the header (FID) from the CSV is used to build a JSON Key, the rest of the header (OBJECTID,SHAPE,LAGE,GRILLPLATZ_ID,RESERVIERUNG,WEBLINK1,SE_ANNO_CAD_DAT) is ignored.
Here is a snippet of my code from the CSV to JSON part.
import org.json.CDL; import org.json.JSONArray; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; public class CSVReader { public static void main(String[] args) { String path = ""; //Insert path to CSV-File here StringBuilder content = new StringBuilder(); String line; String stringtoJSON; try { BufferedReader reader = new BufferedReader(new FileReader(path)); while ((line = reader.readLine()) != null) { content.append(line); content.append(System.lineSeparator()); } stringtoJSON = content.toString(); System.out.println(stringtoJSON); JSONArray jsonArray = CDL.toJSONArray(stringtoJSON); System.out.println(jsonArray); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
One JSON Object of the Array should look like this:
{"FID": "GRILLPLATZOGD.6748", "OBJECTID": "6748", "SHAPE": "POINT (16.465255884594104 48.19018769574157)", "LAGE": "22., Donauinsel, ca. 350 Meter stromab der Steinspornbrücke (Inselmitte, Erdwall)","GRILLPLATZ_ID": "15","RESERVIERUNG": "ja","WEBLINK1":"http://www.wien.gv.at/amtshelfer/umwelt/wasserbau/donauinsel/grillplatzreservierung.html"}
Found the solution with the help of @Skilled_Teaser
I altered his method to this:
public static String removeUnnecessaryQuotes(String s){ String withoutQuotes; withoutQuotes = s.substring(0).replaceAll("\"", ""); withoutQuotes.substring(0).replaceAll("\"\"", "\""); return withoutQuotes; }
and now it works like a charm. Thanks for the help.
-
Can I avoid illgealAccessException when checking if Class private fields are null or empty?
This is the block of code inside the boolean method that I want to check if there are any empty or null fields. It returns true if none of them are. If they are, it throws a custom exception for each case, but it messes up my entire program when it makes me throw the IllegalAccessException.
for(Field f: getClass().getDeclaredFields()) { f.setAccessible(true); try { if((f.get(this)) == null) { throw new NullValueException("Error, this book has null value"); } if(f.get(this).toString().isEmpty()) { throw new ItemEmptyException("Error, this book has null value"); } }catch (IllegalAccessException e) { throw e; } }
Even if I use
f.setAccessible(true)
, it still makes me use try-catch clause for the exception. Can I avoid that try-catch clause and never have to throw an IllegalAccessException? -
Why we need to handle or throw checked exceptions in Java?
I am new to Java, I read that checked exception get raised during compile time only i.e. program will not compile successfully if there is a checked exception which is not handled or thrown. If something is preventing a compiler to compile a code, then we could just erase it or recode it in another way so that problem doesn't exist.
For example, if we are trying to open a file which is not there in system, we should not just open it. So why the need to handle/throw these exceptions ?