.keys() method not working on JSONObject eclipse - java

i am trying to use the .keys() method to get the name of JSON Object's
the code im using is;
Iterator<String> keys = JSONObject.keys();
.keys() is underelined as red on eclipse, i dont know why, can any one help, thanks! -
I have JSON simple as an external library and have imported it, not sure what else to do
EDIT:
Here is more code;
JSONParser parser = new JSONParser();
FileReader testfile = new FileReader("test2.txt");
Object obj = parser.parse(testfile);
JSONObject jsonObject = (JSONObject) obj;
JSONObject name = (JSONObject) jsonObject.get("txt");
String time = (String) name.get("name");
JSONObject example2 = (JSONObject) jsonObject.get("birth");
System.out.println(example2);
Iterator keys = example2 .keys(); <-- where the red line shows up
Second edit:
here are my imports.
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.Set;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

try:
Iterator<String> keys = example2.keySet().iterator();

With this artifact: https://mvnrepository.com/artifact/org.json/json/20170516
Use the following code:
JSONObject obj = new JSONObject("{\"key\":\"value\"}");
for(Object o : obj.keys()) { ... }
It will work.
Do not mix API.

Related

Difference between org.json.simple and org.json

JSONArray js1 = new JSONArray();
for (Product product : plist) {
JSONObject jo1 = new JSONObject();
jo1.put("image", product.getProductImages());
jo1.put("name", product.getName());
jo1.put("price", product.getPrice());
js1.add(jo1);
}
In the above code I can not use js1.add(jo1); because of I import these Libraries.
import org.json.JSONArray;
import org.json.JSONObject;
but if I import these
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
I can use add method.
So what is the difference between these org.json.simple. and org.json.
You have two different dependencies on your classpath.
import org.json.JSONArray;
import org.json.JSONObject;
Above two imports come from JSON-java
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
Above two imports come from json-simple
These are two different implementation of JSON processor. So, it's obvious that the contract of these two dependencies don't match. There are other JSON processor listed on json.org.

JsonObject jar file

I imported the following imports to my code, however I still get an error for
JsonObject obj = new JsonParser().parse(input).getAsJsonObject();
"JsonObject cannot be resolved for a type."
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.json.JSONArray.*;
import org.json.JSONException;
import org.json.JSONObject.*;
import org.json.JSONString;
Its JSONObject not JsonObject.
Same goes for the parser, it's JSONParser not JsonParser.
JSON is always uppercase.

How to send an image with JDA

im developing my Java bot for discord. And I want to send an image. I tried using TextChannel.sendFile(File, Message), but it`s not that result that I want to get. I want this file to be displayed like a normal image.
The imports:
import java.io.File;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import javax.xml.namespace.QName;
import javax.xml.stream.FactoryConfigurationError;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.Attribute;
import javax.xml.stream.events.StartElement;
import javax.xml.stream.events.XMLEvent;
import org.apache.commons.io.FileUtils;
import net.dv8tion.jda.core.MessageBuilder;
import net.dv8tion.jda.core.entities.Message;
import net.dv8tion.jda.core.entities.TextChannel;
import net.dv8tion.jda.core.events.message.MessageReceivedEvent;
And the other code:
URL url = new URL(s.toString());
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
XMLEventReader reader = XMLInputFactory.newInstance().createXMLEventReader(conn.getInputStream());
final List<String> files = new ArrayList<>();
while (reader.hasNext()) {
XMLEvent e = reader.nextEvent();
if (e.isStartElement()) {
StartElement se = e.asStartElement();
if (se.getName().getLocalPart().equals("post")) {
Attribute purl = se.getAttributeByName(new QName("file_url"));
files.add(purl.getValue());
}
}
}
int rid = ThreadLocalRandom.current().nextInt(files.size() - 1);
String p = files.get(rid);
files.clear();
URL u = new URL(p);
final String[] dots = p.split("\\.");
final String format = dots[dots.length - 1];
File f = new File("its not a porn." + format);
FileUtils.copyURLToFile(url, f);
Message m = new MessageBuilder().append("okay :)").build();
c.sendFile(f, m).queue();
}
I tried to find a solution somewhere but i haven found any info that could help.
At JDA 4.2.0_168
the message on sendFile() is the name of the file that you are sending to the discord servers, so it needs an extension
example:
File f = new File("image.png");
TextChannel.sendFile(f, "image.png").queue();
if you want comments in the message
File f = new File("image.png");
//the name doesn't need to be the same, just the same extension
TextChannel.sendFile(f, "another_name.png").append("okay :)").queue();
Result of last code
Reading through the docs, you need to create a MessageEmbed and add it to the message using m.setEmbed(..)

Benders.Strategy using Java and opl

I'm solving a mathematical model using Java however when i tried to call the Benders Strategy i keep receiving this error:
Exception in thread "main" java.lang.IllegalArgumentException: No enum class ilog.cplex.cppimpl.IloCplex$IntParam with value 1501
at ilog.cplex.cppimpl.IloCplex$IntParam.swigToEnum(IloCplex.java:1974)
at ilog.opl.IloCplex.setParam(IloCplex.java:5640)
Here's a part of my code in Java (i'm using CPLEX 12.8 and the library oplall.jar) :
import ilog.concert.IloException;
import ilog.concert.IloIntMap;
import ilog.concert.IloIntSet;
import ilog.concert.IloSymbolSet;
import ilog.opl.IloCplex;
import ilog.opl.IloOplDataSource;
import ilog.opl.IloOplErrorHandler;
import ilog.opl.IloOplFactory;
import ilog.opl.IloOplModel;
import ilog.opl.IloOplModelDefinition;
import ilog.opl.IloOplModelSource;
import ilog.opl.IloOplSettings;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.PrintWriter;
...
IloOplFactory.setDebugMode(false);
IloOplFactory oplF = new IloOplFactory();
IloOplModelSource source = oplF.createOplModelSource("Model.mod");
IloOplDataSource dataSource = oplF.createOplDataSource("Instance.dat");
IloOplErrorHandler handler = oplF.createOplErrorHandler();
IloOplSettings settings = oplF.createOplSettings(handler);
IloOplModelDefinition def = oplF.createOplModelDefinition(source, settings);
IloCplex cplex = new IloCplex();
IloOplModel opl = oplF.createOplModel(def, cplex);
opl.addDataSource(dataSource);
cplex.setParam(IloCplex.IntParam.Benders.Strategy, 3);
opl.generate();
cplex.solve();
cplex.end();
There's a similar question here.
In model.mod you could write:
execute { cplex.bendersstrategy=3; }

How to get Soap header without SOAP handler

I am trying edit my soap header using my java code before running the request. I am not using handler or jax-rs. I saw WsdlUtils but am not able figure how to use this in my code. please someone help me in this
Here's my code;
package soap.impl;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.xmlbeans.XmlException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.eviware.soapui.SoapUI;
import com.eviware.soapui.StandaloneSoapUICore;
import com.eviware.soapui.config.impl.TestStepConfigImpl;
import com.eviware.soapui.impl.wsdl.WsdlHeaderPart;
import com.eviware.soapui.impl.wsdl.WsdlProject;
import com.eviware.soapui.impl.wsdl.WsdlTestSuite;
import com.eviware.soapui.impl.wsdl.submit.filters.SoapHeadersRequestFilter;
import com.eviware.soapui.impl.wsdl.support.wsdl.WsdlUtils;
import com.eviware.soapui.impl.wsdl.support.wsdl.WsdlUtils.SoapHeader;
import com.eviware.soapui.impl.wsdl.testcase.WsdlTestCase;
import com.eviware.soapui.impl.wsdl.testcase.WsdlTestCaseRunner;
import com.eviware.soapui.model.TestPropertyHolder;
import com.eviware.soapui.model.iface.MessageExchange;
import com.eviware.soapui.model.propertyexpansion.PropertyExpansionUtils;
import com.eviware.soapui.model.support.PropertiesMap;
import com.eviware.soapui.model.support.TestPropertyUtils;
import com.eviware.soapui.model.testsuite.TestCase;
import com.eviware.soapui.model.testsuite.TestProperty;
import com.eviware.soapui.model.testsuite.TestRunner;
import com.eviware.soapui.model.testsuite.TestStepResult;
import com.eviware.soapui.model.testsuite.TestRunner.Status;
import com.eviware.soapui.model.testsuite.TestSuite;
import com.eviware.soapui.support.SoapUIException;
import com.eviware.soapui.support.types.StringToObjectMap;
import com.eviware.soapui.support.types.StringToStringsMap;
public class RunTestImpl{
static Logger logger = LoggerFactory.getLogger(RunTestImpl.class);
public static void main(String[] args) throws XmlException, IOException, SoapUIException {
logger.info("Into the Class for running test cases");
String suiteName = "";
String reportStr = "";
InputData input=new InputData();
TestPropertyHolder holder = PropertyExpansionUtils.getGlobalProperties();
String testCaseName="";
holder.setPropertyValue("CRK", "CRK987909000000000075");
// variables for getting duration
WsdlTestCaseRunner runner = null;
List<TestSuite> suiteList = new ArrayList<TestSuite>();
List<TestCase> caseList = new ArrayList<TestCase>();
SoapUI.setSoapUICore(new StandaloneSoapUICore(true));
// specified soapUI project
WsdlProject project1 = new WsdlProject("D://my-project.xml");
WsdlTestSuite testSuite1= project1.getTestSuiteByName("my TestSuite");
WsdlTestCase testCase1= testSuite1.getTestCaseByName("myTestCase");
suiteList.add(testSuite1);
runner= testCase1.run(new StringToObjectMap(), false);
List<TestStepResult> list= runner.getResults();
StringToStringsMap headers1=null;
for (TestStepResult testStepResult : list) {
testStepResult).getRequestContent();
byte[] rawReq=((MessageExchange)testStepResult).getRawRequestData();
headers1 = ((MessageExchange)testStepResult).getRequestHeaders();
String response = ((MessageExchange)testStepResult).getResponseContent();
StringBuilder build=new StringBuilder();
for (byte b : rawReq) {
build.append((char)b);
}
System.out.println("build "+build.toString());
}
for (Map.Entry<String,List< String>> entry : headers1.entrySet()) {
System.out.println("key"+entry.getKey());
for (String string:entry.getValue()) {
System.out.println("value "+string);
}
}
// }
// string of the results
System.out.println(reportStr);
}
}

Categories