i am using rest easy service with tomcat but error Could not find resource for relative.i have created one java file and web.xml and some jars - resteasy

#Path("/dateservice")
public class RestEasyWebapp {
#GET
#Produces(MediaType.TEXT_HTML)
public Response getDate() {
String date = null;
Date currentDate = Calendar.getInstance().getTime();
date = currentDate.toString();
return Response.status(200).entity(date).build();

Related

It is necessary to perform the planned action through the apex scheduler

i have this code:
public static String currencyConverter() {
allCurrency test = new allCurrency();
HttpRequest request = new HttpRequest();
HttpResponse response = new HttpResponse();
Http http = new Http();
request.setEndpoint(endPoint);
request.setMethod('GET');
response = http.send(request);
String JSONresponse = response.getBody();
currencyJSON currencyJSON = (currencyJSON)JSON.deserialize(JSONresponse, currencyJSON.class);
test.USD = currencyJSON.rates.USD;
test.CAD = currencyJSON.rates.CAD;
test.EUR = currencyJSON.rates.EUR;
test.GBP = currencyJSON.rates.GBP;
Log__c logObject = new Log__c();
logObject.Status_Code__c = String.valueOf(response.getStatusCode());
logObject.Response_Body__c = response.getBody();
insert logObject;
if (response.getStatusCode() == 200) {
Exchange_Rate__c ExchangeRateObject = new Exchange_Rate__c();
ExchangeRateObject.CAD__c = currencyJSON.rates.CAD;
ExchangeRateObject.EUR__c = currencyJSON.rates.EUR;
ExchangeRateObject.GBP__c = currencyJSON.rates.GBP;
ExchangeRateObject.USD__c = currencyJSON.rates.USD;
ExchangeRateObject.Log__c = logObject.id;
insert ExchangeRateObject;
}
return JSON.serialize(test);
}
Here I am getting different currencies and then calling them in LWC and also I create two objects with values.
I want these objects to be created every day at 12PM.
Tell me how to implement this through the apex scheduler.
You need a class that implements Schedulable. Can be this class, just add that to the header and add execute method. Or can be separate class, doesn't matter much.
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_scheduler.htm
Something like
public with sharing MyClass implements Schedulable{
public static String currencyConverter() { ... your method here }
public void execute(SchedulableContext sc) {
currencyConverter();
}
}
Once your class saves OK you should be able to schedule it from UI (Setup -> Apex Classes -> button) or with System.schedule 1-liner from Developer Console for example.
Alternative would be to have a scheduled Flow - but that's bit more work with making your Apex callable from Flow.
P.S. Don't name your variables test. Eventually some time later you may need "real" stuff like Test.isRunningTest() and that will be "fun". It's like writing
Integer Account = 5; // happy debugging suckers

parse XML message using SPEL

In my Spring Integration pipeline I am getting a XML payload and depending on the value of the attributes in the XML I have to generate a key and publish it to kafka.
return IntegrationFlows.from(Kafka.messageDrivenChannelAdapter(kafkaListenerContainer))
.wireTap(ACARS_WIRE_TAP_CHNL) // Log the raw message
.enrichHeaders(h ->h.headerFunction(KafkaHeaders.MESSAGE_KEY, m -> {
StringBuilder header = new StringBuilder();
Expression expression = new SpelExpressionParser().parseExpression("payload.Body.toString()");
//Expression expression = new SpelExpressionParser().parseExpression("m.payload.Body.ACIFlight.fltNbr.toString()");
String flightNbr = expression.getValue(String.class);
header.append(flightNbr);
return header.toString();
}))
.get();
XMl is
<?xml version="1.0" encoding="UTF-8"?>
<ns0:Envelope xmlns:ns0="http://www.exmaple.com/FlightLeg">
<ns0:Header>
<ns1:eventHeader xmlns:ns1="http://www.exmaple.com/header" eventID="659" eventName="FlightLegEvent" version="1.0.0">
<ns1:eventSubType>FlightLeg</ns1:eventSubType>
</ns1:eventHeader>
</ns0:Header>
<ns0:Body>
<ns1:ACIFlight xmlns:ns1="http://ual.com/cep/aero/ACIFlight">
<flightKey>1267:07042020:UA</flightKey>
<fltNbr>1267</fltNbr>
<fltLastLegDepDt>07042020</fltLastLegDepDt>
<carrCd>UA</carrCd>
</ns1:ACIFlight>
</ns0:Body>
</ns0:Envelope>
I am trying to get the fltNbr from this xml payload using spel. Please suggest
Updated
String flight = XPathUtils.evaluate(message.getPayload(), "/*[local-name() = 'fltNbr']",XPathUtils.STRING);
String DepDate = XPathUtils.evaluate(message.getPayload(), "/*[local-name() = 'fltLastLegDepDt']",XPathUtils.STRING);
return MessageBuilder.fromMessage(message).setHeader("key", flight+DepDate).build();
You can use the XPath Header Enricher.
XPath is also available as a Spel function, but you'd be better off using the enricher in this case.
public class XPathHeaderEnricher extends HeaderEnricher {
Here's a test case...
#Test
public void convertedEvaluation() {
Map<String, XPathExpressionEvaluatingHeaderValueMessageProcessor> expressionMap =
new HashMap<String, XPathExpressionEvaluatingHeaderValueMessageProcessor>();
XPathExpressionEvaluatingHeaderValueMessageProcessor processor = new XPathExpressionEvaluatingHeaderValueMessageProcessor(
"/root/elementOne");
processor.setHeaderType(TimeZone.class);
expressionMap.put("one", processor);
String docAsString = "<root><elementOne>America/New_York</elementOne></root>";
XPathHeaderEnricher enricher = new XPathHeaderEnricher(expressionMap);
Message<?> result = enricher.transform(MessageBuilder.withPayload(docAsString).build());
MessageHeaders headers = result.getHeaders();
assertThat(headers.get("one")).as("Wrong value for element one expression")
.isEqualTo(TimeZone.getTimeZone("America/New_York"));
}

Should I store XML declaration in database and return using WebApi

Scenario:
User submit XML using WebApi and I want to store it in SQL database in XML Column and retrieve later using Ajax/WebApi
Question:
How should I store it in the database? With or without declaration/encoding? Or should I add the encoding when returning the XML?
public async IActionResult Post([FromBody]XDocument xml)
{
var entity = new MyDocument();
entity.Xml = xml.ToString(); //??
db.Documents.Add(entity);
db.SaveChanges();
return Created();
}
public async Task<IActionResult> Get(int id)
{
var entity = db.Documents.Find(id);
return Content(entity.Xml, "application/xml"); //missing xml declaration
}
My Observations:
XDocument.ToString() trims the XML declaration element:
var xml = XDocument.Load(#"<?xml version=""1.0"" encoding=""utf-8""?>
<Root><Child>Content</Child></Root>");
xml.ToString(); //<Root><Child>Content</Child></Root>
It's easy to include it, but I tought that maybe it's for a reason.
Edge browser does not display the XML when the response does not include xml declaration:
public IActionResult Get()
{
return Content("<Root><Child>Content</Child></Root>", "application/xml")
}
When the response include xml declaration, but the encoding from the declaration does not match response encoding, it also fails with "Unable to switch encodings":
public IActionResult Get()
{
return Content(#"<?xml version=""1.0"" encoding=""utf-8""?>
<Root><Child>Content</Child></Root>", "application/xml");
}
In order to make Edge browser to display the XML properly, I have to do folowing:
public IActionResult Get()
{
string xml = #"<?xml version=""1.0"" encoding=""utf-8""?>
<Root><Child>Content</Child></Root>")
var xmlDoc = XDocument.Parse(xml);
return Content(xml, "application/xml", Encoding.GetEncoding(xmlDoc.Declaration.Encoding));
}
Since database also has some encoding, it's quite unclear to me, what is actually the right way.
I've identified these rules as best practices:
You should not store XML encoding in database
declaration is optional, but if present, it must not include encoding
Your WebApi should always return XML Declaration.
encoding is optional, but if present, it must match response encoding
Explanation:
It's clear that you don't want to store encoding in the database, since the database threats XML columns on it own. However, it makes sense to store XML declaration in the database, because it can contain other information (version, standalone).
Your REST service should always return XML declaration in the response. In case it is not stored in database, you can construct it at runtime.
public async IActionResult Post([FromBody]XDocument xml)
{
var entity = new MyDocument();
var declarationWithoutEncoding = new XDeclaration(xml.Declaration?.Version, null, xml.Declaration?.Standalone);
entity.Xml = $#"{declarationWithoutEncoding}\n\r{xml.ToString()}"
db.Documents.Add(entity);
db.SaveChanges();
return Created();
}
public async Task<IActionResult> Get(int id)
{
var entity = db.Documents.Find(id);
return Content(entity.Xml, "application/xml"); //in case XML Declaration is in database
}
alternativelly
public async Task<IActionResult> Get(int id)
{
var entity = db.Documents.Find(id);
XDocument xmlDoc = XDocument.Parse(entity.xml);
var declaration = new XDeclaration(xml.Declaration?.Version ?? "1.0", null, xml.Declaration?.Standalone ? "no");
//you may change enccoding information to match response encoding, or just skip it
//declaration.Encoding = ...
string xml = $#"{declaration}\n\r{xml.ToString()}"
return Content(xml, "application/xml");
}

Get velocity template from database in Springboot

I have to get velocity templates from database in Spring boot and Spring data project.I have not tried any code yet as I am new to all technologies(Velocity, Spring boot and data) and not finding anything on google. Does anybody tried here to get template from db, please suggest me some links or anything else which i can refer?
Update: I have binding classes in db (in grails) and I have to access process method from java .In db class is ,
class bindingSubject {
def log
def process = { pub,listForMail ->
def mapBinding = [:]
def fund
def perimeters = pub.sub.entities
perimeters.each(){ entity ->
if (fu == null){
if (entity instanceof S)
fu = entity.fu
if (entity instanceof Fund)
fu = fu
}
}mapBinding.entity = fu.name return mapBinding
}
}
and java code written to
-> Load script
mapScriptClass = new HashMap<String, Object>();
if (script != null) {
if (mapScriptClass.get(name) == null) {
GroovyCodeSource groovySource = new GroovyCodeSource(script,name,"");
GroovyClassLoader classLoader = new GroovyClassLoader(this.getClass().getClassLoader());
// Load string as Groovy script class.
Class scriptClass = classLoader.parseClass(groovySource);
try {
Object classInstance = scriptClass.newInstance();
ApplicationContext ctx = (ApplicationContext)ServletContextHolder
.getServletContext().getAttribute(ApplicationAttributes.APPLICATION_CONTEXT);
ctx.getAutowireCapableBeanFactory().autowireBeanProperties(classInstance, AutowireCapableBeanFactory.AUTOWIRE_BY_NAME, false);
mapScriptClass.put(name, classInstance);
return classInstance;
To call process method from db(in grails this works , how to do it in java?)
Object scriptClass = loadScriptService.getScriptClass("scriptBindingSubject"+templateMail.getId(),
templateMail.getScriptBindingSubject());
if (scriptClass != null) {
try{
bindingSubject = scriptClass.process(pub,subMail);
}
now i am not sure how to call process method from java(to db) to bind properties
Thanks.
As you write, the templates are stored in the database.
So you need to read them (using JDBC or JPA) and depending on how they are stored, you will get a String, char[] or byte[].
You can convert all of them into a java.io.Reader like
CharArrayReader, StringReader,
how this can be done for a byte[] you can see in this tutorial
SimpleTemplateEngine has a method
createTemplate(Reader reader)
that finally creates the template for the reader.
Hope that helps.

AppEngine + Datastore + Objectify: Http Request returns inconsistent responses

I am implementing AppEngine server as a backend for my Android application. I use Datastore, I query it via Objectify service and I use Endpoints that I call via URL.
I have an entity User with properties like this:
#Id
Long id;
/**
* Name or nickname of the user
*/
public String name;
#Index
public String email;
#JsonIgnore
List<Key<User>> friends;
public User()
{
devices = new ArrayList<String>();
friendsWithKey = new ArrayList<Key<User>>();
}
public static User findRecordById(Long id)
{
return ofy().load().type(User.class).id(id).now();
}
#ApiMethod(name = "friends", httpMethod = "GET", path = "users/{userId}/friends")
public JSONObject getFriends(#Named("userId") String userId)
{
User user = User.findRecordById(Long.parseLong(userId));
JSONObject friendsObject = new JSONObject();
JSONArray jsonArray = new JSONArray();
JSONObject friend;
List<User> userList = new ArrayList<User>();
if (user.friendsWithKey != null)
{
for (Key<User> id : user.friendsWithKey)
{
friend = new JSONObject();
User user1 = User.findRecordById(id.getId());
userList.add(user1);
friend.put("name", user1.name);
friend.put("email", user1.email);
friend.put("id", user1.id);user1.lastTimeOnline.getTime());
jsonArray.add(friend);
}
friendsObject.put("friends", jsonArray);
}
return friendsObject;
}
It sometimes returns only a subset of friends. It is weird and I do not get where I could go wrong. If I get the User object from the DB, it already has a wrong List of Key values. But if I look into the database via console, I can see all of the users that ahve been added as friends.
I reaally need to fix this bug. Please, help.
It is very strange because it only happens once in a while and is non-deterministic in every way.

Resources