I'm using java spring boot i can print json result on the terminal but i want to show on the web so how can i change this code it to show on web
package com.tutorial.springboot;
import com.google.gson.Gson;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.SimpleDriverDataSource;
import lombok.var;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.sql.Driver;
public class Application {
public static void main(String[] args) throws IOException, ClassNotFoundException{
var prop = new Properties();
prop.load(new FileInputStream("src/main/resources/Application.properties"));
var ds = new SimpleDriverDataSource();
ds.setDriverClass(((Class<Driver>) Class.forName(prop.getProperty("jdbc.driver"))));
ds.setUrl(prop.getProperty("jdbc.url"));
ds.setUsername(prop.getProperty("jdbc.username"));
ds.setPassword(prop.getProperty("jdbc.password"));
var sql = "SELECT * FROM ked_evaluation_data";
var jtm = new JdbcTemplate(ds);
List<Map<String, Object>> rows = (List<Map<String, Object>>) jtm.queryForList(sql);
Gson gson = new Gson();
String jcart=gson.toJson(rows);
System.out.println(jcart);
//rows.forEach(System.out::println);
}
}
In summary, i want to know how to change the code to show the result on web
If someone knows that please teach me!! thank you!
You need to use Spring boot rest controller here like below
#RestController
public class HelloController {
#RequestMapping("/json")
public String index() {
var prop = new Properties();
prop.load(new FileInputStream("src/main/resources/Application.properties"));
var ds = new SimpleDriverDataSource();
ds.setDriverClass(((Class<Driver>) Class.forName(prop.getProperty("jdbc.driver"))));
ds.setUrl(prop.getProperty("jdbc.url"));
ds.setUsername(prop.getProperty("jdbc.username"));
ds.setPassword(prop.getProperty("jdbc.password"));
var sql = "SELECT * FROM ked_evaluation_data";
var jtm = new JdbcTemplate(ds);
List<Map<String, Object>> rows = (List<Map<String, Object>>) jtm.queryForList(sql);
Gson gson = new Gson();
String jcart=gson.toJson(rows);
return jcart;
}
}
Application.java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Call it from the web using url like http://localhost:8080/json
(Replace host and port, also to use rest controller you may need to add dependencies if not already present)
Hope this helps
Related
I have a spring boot app with an Endpoint Test Configuration class and a unit test to test my http client. I am trying to get my server address and port from my application.properties which is located in my src/test.(All the classes are in my src/test.)
Here is my config class code :
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import javax.xml.bind.JAXBException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.ResourceUtils;
import com.nulogix.billing.service.PredictionEngineService;
import com.nulogix.billing.ws.endpoint.AnalyzeEndPoint;
import com.nulogix.billing.ws.endpoint.GetVersionEndPoint;
#Configuration
public class EndPointTestConfiguration {
#Value("${billing.engine.address}")
private String mockAddress;
#Value("${billing.engine.port}")
private String mockPort;
#Bean
public String getAddress() {
String serverAddress = "http://" + mockAddress + ":" + mockPort;
return serverAddress;
}
#Bean
public GetVersionEndPoint getVersionEndPoint() {
return new GetVersionEndPoint();
}
I annotated the values from my .properties with #value and then created a method that I instantiated with a bean to to return my server address string.
I then use that string value here in my HttpClientTest class:
import static org.junit.Assert.*;
import java.io.IOException;
import java.util.Map;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.fluent.Request;
import org.apache.http.entity.ContentType;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ConfigurableApplicationContext;
import com.google.gson.Gson;
import com.nulogix.billing.configuration.EndPointTestConfiguration;
import com.nulogix.billing.mockserver.MockServerApp;
#SpringBootTest(classes = EndPointTestConfiguration.class)
public class HttpClientTest {
#Autowired
EndPointTestConfiguration endpoint;
public static final String request_bad = "ncs|56-2629193|1972-03-28|20190218|77067|6208|3209440|self|";
public static final String request_good = "ncs|56-2629193|1972-03-28|20190218|77067|6208|3209440|self|-123|-123|-123|0.0|0.0|0.0|0.0|0.0|0.0|0.0";
//gets application context
static ConfigurableApplicationContext context;
//call mock server before class
#BeforeClass
static public void setup(){
SpringApplication springApplication = new SpringApplicationBuilder()
.sources(MockServerApp.class)
.build();
context = springApplication.run();
}
//shutdown mock server after class
#AfterClass
static public void tearDown(){
SpringApplication.exit(context);
}
#Test
public void test_bad() throws ClientProtocolException, IOException {
// missing parameter
String result = Request.Post(endpoint.getAddress())
.connectTimeout(2000)
.socketTimeout(2000)
.bodyString(request_bad, ContentType.TEXT_PLAIN)
.execute().returnContent().asString();
Map<?, ?> resultJsonObj = new Gson().fromJson(result, Map.class);
// ensure the key exists
assertEquals(resultJsonObj.containsKey("status"), true);
assertEquals(resultJsonObj.containsKey("errorMessage"), true);
// validate values
Boolean status = (Boolean) resultJsonObj.get("status");
assertEquals(status, false);
String errorMessage = (String) resultJsonObj.get("errorMessage");
assertEquals(errorMessage.contains("Payload has incorrect amount of parts"), true);
}
#Test
public void test_good() throws ClientProtocolException, IOException {
String result = Request.Post(endpoint.getAddress())
.connectTimeout(2000)
.socketTimeout(2000)
.bodyString(request_good, ContentType.TEXT_PLAIN)
.execute().returnContent().asString();
Map<?, ?> resultJsonObj = new Gson().fromJson(result, Map.class);
// ensure the key exists
assertEquals(resultJsonObj.containsKey("status"), true);
assertEquals(resultJsonObj.containsKey("errorMessage"), false);
assertEquals(resultJsonObj.containsKey("HasCopay"), true);
assertEquals(resultJsonObj.containsKey("CopayAmount"), true);
assertEquals(resultJsonObj.containsKey("HasCoinsurance"), true);
assertEquals(resultJsonObj.containsKey("CoinsuranceAmount"), true);
assertEquals(resultJsonObj.containsKey("version"), true);
// validate values
Boolean status = (Boolean) resultJsonObj.get("status");
assertEquals(status, true);
String version = (String) resultJsonObj.get("version");
assertEquals(version, "0.97");
}
}
I use it in the request.post, I didn't want to hardcode in my IP address and port number.
When I run the test it says
[ERROR] HttpClientTest.test_bad:63 NullPointer
[ERROR] HttpClientTest.test_good:86 NullPointer
But I am not sure why it is null? I am pretty sure I have everything instantiated and the string is clearly populated..
My package structure for my config is com.billing.mockserver and my package structure for my unit test is com.billing.ws.endpoint.
Here is my application.properties
server.port=9119
server.ssl.enabled=false
logging.config=classpath:logback-spring.xml
logging.file=messages
logging.file.max-size=50MB
logging.level.com.nulogix=DEBUG
billing.engine.address=127.0.0.1
billing.engine.port=9119
billing.engine.api.version=0.97
billing.engine.core.name=Patient_Responsibility
You are missing springboot basic understanding. #Configuration class is to initialize other spring beans and other things and are the first classes which get initialized. You should not #Autowire #configuration class.
In your Configuration class you can either create Spring bean for username and password and autowire that in your test class or directly use #Value in your Test class.
Example: in your configuration class you are creating bean of GetVersionEndPoint and you can autowire that in your Test class.
Update 2:
For test classes, you need to add application.properties file in src\test\resource
I want to run particular testStep of my testcase of soap ui using java code. My problem is when I try to run at test step level it need argument of TestCase runner which is anonymous inner type and TestCaseRunContext which is interface. Do I have to implement both to run the same? if yes can please any sample how to do that??
here's my code
package com.testauto.soaprunner.soap.impl;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.eviware.soapui.SoapUI;
import com.eviware.soapui.StandaloneSoapUICore;
import com.eviware.soapui.impl.wsdl.WsdlProject;
import com.eviware.soapui.impl.wsdl.WsdlTestSuite;
import com.eviware.soapui.impl.wsdl.testcase.WsdlTestCase;
import com.eviware.soapui.impl.wsdl.testcase.WsdlTestCaseRunner;
import com.eviware.soapui.impl.wsdl.teststeps.WsdlTestStep;
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.testsuite.TestCase;
import com.eviware.soapui.model.testsuite.TestCaseRunContext;
import com.eviware.soapui.model.testsuite.TestProperty;
import com.eviware.soapui.model.testsuite.TestStepResult;
import com.eviware.soapui.model.testsuite.TestSuite;
import com.eviware.soapui.support.types.StringToObjectMap;
import com.eviware.soapui.support.types.StringToStringsMap;
import com.testauto.soaprunner.data.InputData;
import com.testauto.soaprunner.data.ReportData;
public class RunTestImpl{
static Logger logger = LoggerFactory.getLogger(RunTestImpl.class);
List<ReportData> reportDatList=new ArrayList<ReportData>();
public List<ReportData> process(Map<String, String> readDataMap, InputData input, Map<List<String>, String> configurationMap, List<String> configuration, WsdlTestSuite testSuite)
{
List<ReportData> report = new ArrayList<ReportData>();
logger.info("Into the Class for running test cases");
try{
report= getTestSuite(readDataMap,input,configurationMap,configuration,testSuite);
}
catch(Exception e)
{
logger.info(e.getMessage());
}
return report;
}
private List<ReportData> getTestSuite(Map<String, String> readDataMap, InputData input, Map<List<String>, String> configurationMap, List<String> configuration, WsdlTestSuite testSuite) throws Exception {
ReportData report=new ReportData();
logger.info("Into the Class for running test cases");
String suiteName = "";
String reportStr = "";
List<String> testCaseNameList= setPropertyValues(readDataMap,input);
WsdlTestCaseRunner runner = null;
List<TestSuite> suiteList = new ArrayList<TestSuite>();
List<TestCase> caseList = new ArrayList<TestCase>();
SoapUI.setSoapUICore(new StandaloneSoapUICore(true));
System.out.println("testcase name "+ configurationMap.get(configuration));
// WsdlTestCase testCase= testSuite.getTestCaseByName(input.getApiName()+"_"+testCaseName+"_TestCase");
WsdlTestCase testCase= testSuite.getTestCaseByName("my_TESTCASE");
WsdlTestStep tesStep=testCase.getTestStepByName(configurationMap.get(testCaseNameList));
System.out.println("test case name:"+testCase.getName());
report.setTestCase(testCase.getName());
suiteList.add(testSuite);
runner= tesStep.run(?,?);
return reportDatList;
}
private List<String> setPropertyValues(Map<String, String> readDataMap, InputData input) {
String testCaseName="";
TestPropertyHolder holder = PropertyExpansionUtils.getGlobalProperties();
List<String> dataConfigurationList=new ArrayList<String>();
Iterator entries = readDataMap.entrySet().iterator();
while (entries.hasNext()) {
Entry thisEntry = (Entry) entries.next();
String key = (String) thisEntry.getKey();
String value = (String) thisEntry.getValue();
testCaseName+=key;
holder.setPropertyValue(key, holder.getPropertyValue(key));
dataConfigurationList.add(key);
}
System.out.println("testCaseName"+testCaseName);
return dataConfigurationList;
}
}
}
After trying different things I got something like this.
TestCaseRunContext context = new MockTestRunContext(new MockTestRunner(testStep.getTestCase()), testStep);
MockTestRunner runner = new MockTestRunner(testStep.getTestCase());
TestStepResult testStepResult= testStep.run(runner, context);
I don't know how it works this trick worked for me. if someone know the reason behind this please share
I'm trying to marshal an Object into a csv String. I have created a method that can convert any object into a csv String but I keep getting the exception:
java.lang.NoSuchMethodError: org.codehaus.jackson.map.ObjectMapper.writer(Lorg/codehaus/jackson/FormatSchema;)Lorg/codehaus/jackson/map/ObjectWriter;
Marshal method:
public static final synchronized String marshal(final Object object, final CsvSchema csvSchema) throws IOException {
String CSV_FILTER_NAME = "csvFilter";
HashSet<String> columnNames = new HashSet<>();
for (CsvSchema.Column column : csvSchema) {
columnNames.add(column.getName());
}
SimpleBeanPropertyFilter csvReponseFilter = new SimpleBeanPropertyFilter.FilterExceptFilter(columnNames);
FilterProvider filterProvider = new SimpleFilterProvider().addFilter(CSV_FILTER_NAME, csvReponseFilter);
CsvMapper csvMapper = new CsvMapper();
csvMapper.setFilters(filterProvider);
csvMapper.setAnnotationIntrospector(new JacksonAnnotationIntrospector() {
#Override
public Object findFilterId(AnnotatedClass annotatedClass) {
return CSV_FILTER_NAME;
}
});
ObjectWriter objectWriter = csvMapper.writer(csvSchema);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
objectWriter.writeValue(byteArrayOutputStream, csvSchema);
return new String(byteArrayOutputStream.toByteArray(), "UTF-8");
}
Main method:
public static void main(String args[]) {
CsvSchema csvSchema = CsvSchema.builder()
.addColumn("name")
.addColumn("age")
.addColumn("height")
.addColumn("weight")
.setUseHeader(true)
.build()
.withLineSeparator("\n");
Person person = new Person("Tim", "32", "184", "100");
try {
System.out.println(CsvUtilities.marshal(person, csvSchema));
} catch (IOException ex) {
Logger.getLogger(CsvUtilities.class.getName()).log(Level.SEVERE, null, ex);
}
}
What is causing this exception?
EDIT Here's all my imports:
import com.fasterxml.jackson.dataformat.csv.CsvMapper;
import com.fasterxml.jackson.dataformat.csv.CsvSchema;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.List;
import java.util.logging.Logger;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.codehaus.jackson.map.ObjectWriter;
import org.codehaus.jackson.map.introspect.AnnotatedClass;
import org.codehaus.jackson.map.introspect.JacksonAnnotationIntrospector;
import org.codehaus.jackson.map.ser.FilterProvider;
import org.codehaus.jackson.map.ser.impl.SimpleBeanPropertyFilter;
import org.codehaus.jackson.map.ser.impl.SimpleFilterProvider;
See the jars in your class path. It could be that there are two or different version of jackson jar which does not have this method. Maybe an older version been laoded in by the Class loader.
Also inspect your dependencies which you have added to the project.
Is it possible to return the type of an entities (e.g Location)
just like how the freebase search works? I am using freebase search sample codes (I'll provide them below) to generate the search results but even using the wildcard, it does not extract the entity types, here are some of the sample results.
SAMPLE RESULTS
["\/en\/bukit_panjang","Bukit Panjang",284.883636,"\/m\/04fxxf","en"]
["\/en\/bukit_panjang_mrt_station",{"id":"\/metropolitan_transit\/transit_stop","name":"Transit Stop"},"Bukit Panjang LRT\/MRT Station",250.857147,"\/m\/0661mk1","en"]
["\/en\/bukit_panjang_plaza",{"id":"\/business\/shopping_center","name":"Shopping center"},"Bukit Panjang Plaza",229.566818,"\/m\/02q_h6s","en"]
SEARCH SAMPLE CODES
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.jayway.jsonpath.JsonPath;
import java.io.FileInputStream;
import java.util.Properties;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
public class SearchSample {
public static Properties properties = new Properties();
public static void main(String[] args) {
try {
properties.load(new FileInputStream("freebase.properties"));
HttpTransport httpTransport = new NetHttpTransport();
HttpRequestFactory requestFactory = httpTransport.createRequestFactory();
JSONParser parser = new JSONParser();
GenericUrl url = new GenericUrl("https://www.googleapis.com/freebase/v1/search");
url.put("query", "Bukit Panjang");
//url.put("filter", "(any type:/people/person domain:location/citytown/)");
url.put("filter", "(any part_of:singapore)");
url.put("limit", "10");
url.put("indent", "true");
url.put("key", properties.get("API_KEY"));
HttpRequest request = requestFactory.buildGetRequest(url);
HttpResponse httpResponse = request.execute();
JSONObject response = (JSONObject)parser.parse(httpResponse.parseAsString());
JSONArray results = (JSONArray)response.get("result");
for (Object result : results) {
System.out.println(JsonPath.read(result,"$.*").toString());
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
Use the output parameter to tailor the output, as described on this page:
https://developers.google.com/freebase/v1/search-output
e.g.
https://www.googleapis.com/freebase/v1/search?indent=true&filter=%28all+name%7Bfull%7D%3A%22Bukit+Panjang%22+part_of:singapore%29&output=%28type%29
(although you may want to consider using the notable_type or notable_for instead of raw type, depending on what your goal is)
I am trying to query vendors using the QBOVendorService but having no luck.
I am creating the service as follows:
QBOVendorService vService = QBServiceFactory.getService(context, QBOVendorService.class);
where the context is a valid PlatformSessionContext. I know the platform session context is good since I can get information about the user with it. When I try
vService.addVendor(context, vendor);
I end up with a NPE like my vService is null. Shouldn't I get an error initializing the QBOVendorService if it fails? Is there a good place to find more examples for using this since the intuit developer forums have been shut down?
I'm sharing a sample code snippet. Replace your OAuth tokens and relamId. It should work fine.
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;
import com.intuit.ds.qb.QBIdType;
import com.intuit.ds.qb.QBVendor;
import com.intuit.ds.qb.QBVendorQuery;
import com.intuit.ds.qb.QBVendorService;
import com.intuit.ds.qb.QBInvalidContextException;
import com.intuit.ds.qb.QBObjectFactory;
import com.intuit.ds.qb.QBServiceFactory;
import com.intuit.ds.qb.impl.QBRecordCountImpl;
import com.intuit.ds.qb.qbd.QBDRecordCountService;
import com.intuit.ds.qb.qbd.QBDServiceFactory;
import com.intuit.platform.client.PlatformSessionContext;
import com.intuit.platform.client.PlatformServiceType;
import com.intuit.platform.client.security.OAuthCredentials;
import com.intuit.ds.qb.QBSyncStatusRequest;
import com.intuit.ds.qb.QBSyncStatusRequestService;
import com.intuit.ds.qb.QBSyncStatusResponse;
import com.intuit.sb.cdm.NgIdSet;
import com.intuit.sb.cdm.ObjectName;
import org.slf4j.Logger;
// QBD API Docs - https://developer.intuit.com/docs/0025_quickbooksapi/0050_data_services/v2/0500_quickbooks_windows/0600_object_reference/vendor
// QBO API Docs - https://developer.intuit.com/docs/0025_quickbooksapi/0050_data_services/v2/0400_quickbooks_online/vendor
// JavaDocs - http://developer-static.intuit.com/SDKDocs/QBV2Doc/ipp-java-devkit-2.0.10-SNAPSHOT-javadoc/
public class CodegenStubVendorall {
final PlatformSessionContext context;
public CodegenStubVendorall(PlatformSessionContext context) {
this.context = context;
}
public void testAdd() {
final List<QBVendor> entityList = new ArrayList<QBVendor>();
try {
QBVendorService service = QBServiceFactory.getService(context, QBVendorService.class);
//Your Code
//Use Vendor POJO for creating Vendor
}
} catch (QBInvalidContextException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String args[]) {
PlatformSessionContext context = getPlatformContext();
CodegenStubVendorall testObj = new CodegenStubVendorall(context);
testObj.testAdd();
}
public static PlatformSessionContext getPlatformContext() {
String accesstoken = "rplce_your_application_token";
String accessstokensecret = "rplce_your_application_token";
String appToken = "rplce_your_application_token";
String oauth_consumer_key = "rplce_your_application_token";
String oauth_consumer_secret = "rplce_your_application_token";
String realmID = "123456";
String dataSource = "QBO";
PlatformServiceType serviceType;
if (dataSource.equalsIgnoreCase("QBO")) {
serviceType = PlatformServiceType.QBO;
} else {
serviceType = PlatformServiceType.QBD;
}
final OAuthCredentials oauthcredentials = new OAuthCredentials(
oauth_consumer_key, oauth_consumer_secret, accesstoken,
accessstokensecret);
final PlatformSessionContext context = new PlatformSessionContext(
oauthcredentials, appToken, serviceType, realmID);
return context;
}
}
You can try to use ApiExplorer tool to verify your OAuth tokens and to check the create Vendor API endpoint.
Link - https://developer.intuit.com/apiexplorer?apiname=V2QBO
Please let me know how it goes.
Thanks