MVEL extracting a string from a string - mvel

I have the strings "000134567 - AA - 2001" and "002134567 - AB - 2001" and I want to extract all the numbers before the " - AA". But I only want to return the numbers starting from the first non-zero number. For example, I would want "134567" or "2134567".
Is there some function that would allow me to do this using MVEL? Any help is appreciated.

I do not think directly we can use MVEL for this, but yes tweaking little bit might help us.
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import org.mvel2.MVEL;
import org.mvel2.ParserContext;
import org.mvel2.integration.VariableResolverFactory;
import org.mvel2.integration.impl.MapVariableResolverFactory;
public class MyTest {
public static void main(String[] args) {
String myString = "000134567 - AA - 2001";
Map contextMap = new HashMap();
contextMap.put("myString", myString);
ParserContext ctx = new ParserContext();
ctx.addPackageImport("java.util.regex");
Serializable s = MVEL.compileExpression("outputString(myString)", ctx);
System.out.println(MVEL.executeExpression(s, contextMap, getMvelFactory(contextMap)));
}
private static VariableResolverFactory getMvelFactory(Map contextMap) {
VariableResolverFactory functionFactory = new MapVariableResolverFactory(contextMap);
MVEL.eval(
"outputString = def (myString) { java.util.regex.Pattern p = java.util.regex.Pattern.compile(\"[0-9]+\"); java.util.regex.Matcher m = p.matcher(myString); if (m.find()) { String output = m.group(); return output.replaceAll(\"^0+\", \"\");}};",
functionFactory);
return functionFactory;
}
}
Function
Below is my function written in java which i have included inside Mvel VariableResolverFactory.
outputString = def (myString) {
java.util.regex.Pattern p = java.util.regex.Pattern.compile("[0-9]+");
Matcher m = p.matcher(myString);
if (m.find()) {
String output = m.group();
return output.replaceAll("^0+", "");
}
};
Creating Parser Context and adding import
Since java.util.regex package is not available with MVEL, so we will import this package explicitly.
ParserContext ctx = new ParserContext();
ctx.addPackageImport("java.util.regex");
Compiling Expression using above Import
This will just compile the expression and will add imports for later use while evaluation.
Serializable s = MVEL.compileExpression("outputString(myString)", ctx);
Varying variable
You can pass through your variables as below,
Map contextMap = new HashMap();
contextMap.put("myString", myString);
Rest you can change the function body, signature and return statement as per your needs.

Related

How do you use the LauncherDiscoveryRequestBuilder to execute a test method that has a parameter of type TestInfo?

I tried out all the different method selectors as seen on this page: https://junit.org/junit5/docs/current/api/org/junit/platform/launcher/core/LauncherDiscoveryRequestBuilder.html
For example tried to do it like so:
selectMethod("org.example.order.OrderTests#test3"),
like so:
selectMethod("org.example.order.OrderTests#test3(TestInfo)"),
or like so: selectMethod("org.example.order.OrderTests#test3(org.junit.jupiter.engine.extension.TestInfoParameterResolver$DefaultTestInfo)")
Each time, no tests are found.
When I only select the class the method resides in, it works: selectClass("org.example.order.OrderTests")
(but I'm looking to call the method explicitly)
I am assuming the behavior is the same for other parameter types that are resolved at runtime by a ParameterResolver.
Your assumption is wrong. You can select one and only one test method.
As you mentioned on this page Discovery Selectors there are a lot of examples.
DiscoverySelectors.selectMethod provide three way to select desired method(s)
public static MethodSelector selectMethod(String className, String methodName, String methodParameterTypes) {
...
}
public static MethodSelector selectMethod(String className, String methodName) {
...
}
and
public static MethodSelector selectMethod(String fullyQualifiedMethodName) throws PreconditionViolationException {
...
}
You've tried to use the last method but the fullyQualifiedMethodName was wrong a little bit. If you take a look on javadoc it will turn up.
Parameter type list must exactly match and every non-primitive types must be fully qualified as well.
In your example the package is missing. Try it like: selectMethod("org.example.order.OrderTests#test3(org.junit.jupiter.api.TestInfo)")
Here is a short test.
package io.github.zforgo.stackoverflow;
import org.junit.jupiter.api.RepeatedTest;
import org.junit.jupiter.api.RepetitionInfo;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInfo;
public class ClassWithTestInfo {
#Test
void foo() {
}
#Test
void foo(TestInfo info) {
}
#RepeatedTest(3)
void foo(RepetitionInfo info) {
}
}
package io.github.zforgo.stackoverflow;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.engine.descriptor.MethodBasedTestDescriptor;
import org.junit.platform.engine.DiscoverySelector;
import org.junit.platform.engine.FilterResult;
import org.junit.platform.engine.discovery.DiscoverySelectors;
import org.junit.platform.launcher.LauncherDiscoveryRequest;
import org.junit.platform.launcher.PostDiscoveryFilter;
import org.junit.platform.launcher.core.LauncherDiscoveryRequestBuilder;
import org.junit.platform.launcher.core.LauncherFactory;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
class DiscoveryTest {
#Test
#DisplayName("Should select only the desired method(s)")
void doTEst() {
Assertions.assertAll(
() -> {
var methods = discover(DiscoverySelectors.selectClass(ClassWithTestInfo.class));
Assertions.assertEquals(3, methods.size());
},
() -> {
// your way
var fqmn = "io.github.zforgo.stackoverflow.ClassWithTestInfo#foo(TestInfo)";
var methods = discover(DiscoverySelectors.selectMethod(fqmn));
Assertions.assertEquals(0, methods.size());
},
() -> {
// good way
var fqmn = "io.github.zforgo.stackoverflow.ClassWithTestInfo#foo(org.junit.jupiter.api.TestInfo)";
var methods = discover(DiscoverySelectors.selectMethod(fqmn));
Assertions.assertEquals(1, methods.size());
}
);
}
private List<Method> discover(DiscoverySelector... selectors) {
final List<Method> methodCollector = new ArrayList<>();
LauncherDiscoveryRequest request = LauncherDiscoveryRequestBuilder.request()
.selectors(selectors)
.filters((PostDiscoveryFilter) object -> {
Method m = ((MethodBasedTestDescriptor) object).getTestMethod();
methodCollector.add(m);
return FilterResult.included("Matched");
})
.build();
LauncherFactory.create().discover(request);
return methodCollector;
}
}

How do I configure spring-kafka to ignore messages in the wrong format?

We have an issue with one of our Kafka topics which is consumed by the DefaultKafkaConsumerFactory & ConcurrentMessageListenerContainer combination described here with a JsonDeserializer used by the Factory. Unfortunately someone got a little enthusiastic and published some invalid messages onto the topic. It appears that spring-kafka silently fails to process past the first of these messages. Is it possible to have spring-kafka log an error and continue? Looking at the error messages which are logged it seems that perhaps the Apache kafka-clients library should deal with the case that when iterating a batch of messages one or more of them may fail to parse?
The below code is an example test case illustrating this issue:
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.common.serialization.Serializer;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;
import org.junit.ClassRule;
import org.junit.Test;
import org.springframework.kafka.core.DefaultKafkaConsumerFactory;
import org.springframework.kafka.core.DefaultKafkaProducerFactory;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.listener.KafkaMessageListenerContainer;
import org.springframework.kafka.listener.MessageListener;
import org.springframework.kafka.listener.config.ContainerProperties;
import org.springframework.kafka.support.SendResult;
import org.springframework.kafka.support.serializer.JsonDeserializer;
import org.springframework.kafka.support.serializer.JsonSerializer;
import org.springframework.kafka.test.rule.KafkaEmbedded;
import org.springframework.kafka.test.utils.ContainerTestUtils;
import org.springframework.util.concurrent.ListenableFuture;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.springframework.kafka.test.hamcrest.KafkaMatchers.hasKey;
import static org.springframework.kafka.test.hamcrest.KafkaMatchers.hasValue;
/**
* #author jfreedman
*/
public class TestSpringKafka {
private static final String TOPIC1 = "spring.kafka.1.t";
#ClassRule
public static KafkaEmbedded embeddedKafka = new KafkaEmbedded(1, true, 1, TOPIC1);
#Test
public void submitMessageThenGarbageThenAnotherMessage() throws Exception {
final BlockingQueue<ConsumerRecord<String, JsonObject>> records = createListener(TOPIC1);
final KafkaTemplate<String, JsonObject> objectTemplate = createPublisher("json", new JsonSerializer<JsonObject>());
sendAndVerifyMessage(records, objectTemplate, "foo", new JsonObject("foo"), 0L);
// push some garbage text to Kafka which cannot be marshalled, this should not interrupt processing
final KafkaTemplate<String, String> garbageTemplate = createPublisher("garbage", new StringSerializer());
final SendResult<String, String> garbageResult = garbageTemplate.send(TOPIC1, "bar","bar").get(5, TimeUnit.SECONDS);
assertEquals(1L, garbageResult.getRecordMetadata().offset());
sendAndVerifyMessage(records, objectTemplate, "baz", new JsonObject("baz"), 2L);
}
private <T> KafkaTemplate<String, T> createPublisher(final String label, final Serializer<T> serializer) {
final Map<String, Object> producerProps = new HashMap<>();
producerProps.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, embeddedKafka.getBrokersAsString());
producerProps.put(ProducerConfig.CLIENT_ID_CONFIG, "TestPublisher-" + label);
producerProps.put(ProducerConfig.ACKS_CONFIG, "all");
producerProps.put(ProducerConfig.RETRIES_CONFIG, 2);
producerProps.put(ProducerConfig.MAX_IN_FLIGHT_REQUESTS_PER_CONNECTION, 1);
producerProps.put(ProducerConfig.REQUEST_TIMEOUT_MS_CONFIG, 5000);
producerProps.put(ProducerConfig.MAX_BLOCK_MS_CONFIG, 5000);
producerProps.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
producerProps.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, serializer.getClass());
final DefaultKafkaProducerFactory<String, T> pf = new DefaultKafkaProducerFactory<>(producerProps);
pf.setValueSerializer(serializer);
return new KafkaTemplate<>(pf);
}
private BlockingQueue<ConsumerRecord<String, JsonObject>> createListener(final String topic) throws Exception {
final Map<String, Object> consumerProps = new HashMap<>();
consumerProps.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, embeddedKafka.getBrokersAsString());
consumerProps.put(ConsumerConfig.GROUP_ID_CONFIG, "TestConsumer");
consumerProps.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, true);
consumerProps.put(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG, "100");
consumerProps.put(ConsumerConfig.SESSION_TIMEOUT_MS_CONFIG, 15000);
consumerProps.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
consumerProps.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, JsonDeserializer.class);
final DefaultKafkaConsumerFactory<String, JsonObject> cf = new DefaultKafkaConsumerFactory<>(consumerProps);
cf.setValueDeserializer(new JsonDeserializer<>(JsonObject.class));
final KafkaMessageListenerContainer<String, JsonObject> container = new KafkaMessageListenerContainer<>(cf, new ContainerProperties(topic));
final BlockingQueue<ConsumerRecord<String, JsonObject>> records = new LinkedBlockingQueue<>();
container.setupMessageListener((MessageListener<String, JsonObject>) records::add);
container.setBeanName("TestListener");
container.start();
ContainerTestUtils.waitForAssignment(container, embeddedKafka.getPartitionsPerTopic());
return records;
}
private void sendAndVerifyMessage(final BlockingQueue<ConsumerRecord<String, JsonObject>> records,
final KafkaTemplate<String, JsonObject> template,
final String key, final JsonObject value,
final long expectedOffset) throws InterruptedException, ExecutionException, TimeoutException {
final ListenableFuture<SendResult<String, JsonObject>> future = template.send(TOPIC1, key, value);
final ConsumerRecord<String, JsonObject> record = records.poll(5, TimeUnit.SECONDS);
assertThat(record, hasKey(key));
assertThat(record, hasValue(value));
assertEquals(expectedOffset, future.get(5, TimeUnit.SECONDS).getRecordMetadata().offset());
}
public static final class JsonObject {
private String value;
public JsonObject() {}
JsonObject(final String value) {
this.value = value;
}
public String getValue() {
return value;
}
public void setValue(final String value) {
this.value = value;
}
#Override
public boolean equals(final Object o) {
if (this == o) { return true; }
if (o == null || getClass() != o.getClass()) { return false; }
final JsonObject that = (JsonObject) o;
return Objects.equals(value, that.value);
}
#Override
public int hashCode() {
return Objects.hash(value);
}
#Override
public String toString() {
return "JsonObject{" +
"value='" + value + '\'' +
'}';
}
}
}
I have a solution but I don't know if it's the best one, I extended JsonDeserializer as follows which results in a null value being consumed by spring-kafka and requires the necessary downstream changes to handle that case.
class SafeJsonDeserializer[A >: Null](targetType: Class[A], objectMapper: ObjectMapper) extends JsonDeserializer[A](targetType, objectMapper) with Logging {
override def deserialize(topic: String, data: Array[Byte]): A = try {
super.deserialize(topic, data)
} catch {
case e: Exception =>
logger.error("Failed to deserialize data [%s] from topic [%s]".format(new String(data), topic), e)
null
}
}
Starting from the spring-kafka-2.x.x, we now have the comfort of declaring beans in the config file for the interface KafkaListenerErrorHandler with a implementation something as
#Bean
public ConsumerAwareListenerErrorHandler listen3ErrorHandler() {
return (m, e, c) -> {
this.listen3Exception = e;
MessageHeaders headers = m.getHeaders();
c.seek(new org.apache.kafka.common.TopicPartition(
headers.get(KafkaHeaders.RECEIVED_TOPIC, String.class),
headers.get(KafkaHeaders.RECEIVED_PARTITION_ID, Integer.class)),
headers.get(KafkaHeaders.OFFSET, Long.class));
return null;
};
}
more resources can be found at https://docs.spring.io/spring-kafka/reference/htmlsingle/#annotation-error-handling There is also another link with the similar issue: Spring Kafka error handling - v1.1.x and How to handle SerializationException after deserialization
Use ErrorHandlingDeserializer2. This is a delegating key/value deserializer that catches exceptions, returning them in the headers as serialized java objects.
Under consumer configuration, add/update the below lines:
import org.apache.kafka.clients.consumer.ConsumerConfig
import org.springframework.kafka.support.serializer.ErrorHandlingDeserializer2
configProps.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG,
classOf[ErrorHandlingDeserializer2[JsonDeserializer]].getName)
configProps.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, classOf[ErrorHandlingDeserializer2[StringDeserializer]].getName)
configProps.put(ErrorHandlingDeserializer2.KEY_DESERIALIZER_CLASS, classOf[StringDeserializer].getName)
configProps.put(ErrorHandlingDeserializer2.VALUE_DESERIALIZER_CLASS, classOf[JsonDeserializer].getName)

How to use Google QPX API with Java for flight search?

I am trying to build a simple Java code that obtains flight options using Google QPX API, for the flight from New York to London. I signed up with Google and got API_key.
I read the documentation, but unfortunately, I couldn't find any example that show me how to do it.
Here what I tried so far:
import com.google.api.services.qpxExpress.model.*;
import java.util.*;
public class Main
{
public static void main(String[] args)
{
// Passengers
PassengerCounts passengers = new PassengerCounts();
passengers.setAdultCount(2);
// Slice
List<SliceInput> slices = new ArrayList<SliceInput>();
SliceInput slice = new SliceInput();
slice.setOrigin("JFK"); // John Kennedy Airport in Ney York
slice.setDestination("LHR"); // London Heathrow
slice.setDate("2015-07-01");
slices.add(slice);
// Options request
TripOptionsRequest tripOptions = new TripOptionsRequest();
tripOptions.setPassengers(passengers);
tripOptions.setSlice(slices);
// Search request
TripsSearchRequest tripSearchReq = new TripsSearchRequest();
tripSearchReq.setRequest(tripOptions);
// Next steps?
// Setting up QPXExpress?
}
}
I will appreciate it if someone can help me to complete the code.
Thanks in advance.
This is a simple code, successfully tested, hope it helps
package com.airline.api;
import java.io.IOException;
import java.util.*;
import javax.swing.text.View;
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.qpxExpress.QPXExpressRequestInitializer;
import com.google.api.services.qpxExpress.QPXExpress;
import com.google.api.services.qpxExpress.model.FlightInfo;
import com.google.api.services.qpxExpress.model.LegInfo;
import com.google.api.services.qpxExpress.model.PassengerCounts;
import com.google.api.services.qpxExpress.model.PricingInfo;
import com.google.api.services.qpxExpress.model.SegmentInfo;
import com.google.api.services.qpxExpress.model.SliceInfo;
import com.google.api.services.qpxExpress.model.TripOption;
import com.google.api.services.qpxExpress.model.TripOptionsRequest;
import com.google.api.services.qpxExpress.model.TripsSearchRequest;
import com.google.api.services.qpxExpress.model.SliceInput;
import com.google.api.services.qpxExpress.model.TripsSearchResponse;
public class AirlineReservation {
/**
* #param args
*/
private static final String APPLICATION_NAME = "MyFlightApplication";
private static final String API_KEY = "AIzaSyDnBCdsmTnrL5XFrO2TjJyvFioswjakNYU";
/** Global instance of the HTTP transport. */
private static HttpTransport httpTransport;
/** Global instance of the JSON factory. */
private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
httpTransport = GoogleNetHttpTransport.newTrustedTransport();
PassengerCounts passengers= new PassengerCounts();
passengers.setAdultCount(1);
List<SliceInput> slices = new ArrayList<SliceInput>();
SliceInput slice = new SliceInput();
slice.setOrigin("NYC");
slice.setDestination("LGA");
slice.setDate("2015-04-29");
slices.add(slice);
TripOptionsRequest request= new TripOptionsRequest();
request.setSolutions(10);
request.setPassengers(passengers);
request.setSlice(slices);
TripsSearchRequest parameters = new TripsSearchRequest();
parameters.setRequest(request);
QPXExpress qpXExpress= new QPXExpress.Builder(httpTransport, JSON_FACTORY, null).setApplicationName(APPLICATION_NAME)
.setGoogleClientRequestInitializer(new QPXExpressRequestInitializer(API_KEY)).build();
TripsSearchResponse list= qpXExpress.trips().search(parameters).execute();
List<TripOption> tripResults=list.getTrips().getTripOption();
String id;
for(int i=0; i<tripResults.size(); i++){
//Trip Option ID
id= tripResults.get(i).getId();
System.out.println("id "+id);
//Slice
List<SliceInfo> sliceInfo= tripResults.get(i).getSlice();
for(int j=0; j<sliceInfo.size(); j++){
int duration= sliceInfo.get(j).getDuration();
System.out.println("duration "+duration);
List<SegmentInfo> segInfo= sliceInfo.get(j).getSegment();
for(int k=0; k<segInfo.size(); k++){
String bookingCode= segInfo.get(k).getBookingCode();
System.out.println("bookingCode "+bookingCode);
FlightInfo flightInfo=segInfo.get(k).getFlight();
String flightNum= flightInfo.getNumber();
System.out.println("flightNum "+flightNum);
String flightCarrier= flightInfo.getCarrier();
System.out.println("flightCarrier "+flightCarrier);
List<LegInfo> leg=segInfo.get(k).getLeg();
for(int l=0; l<leg.size(); l++){
String aircraft= leg.get(l).getAircraft();
System.out.println("aircraft "+aircraft);
String arrivalTime= leg.get(l).getArrivalTime();
System.out.println("arrivalTime "+arrivalTime);
String departTime=leg.get(l).getDepartureTime();
System.out.println("departTime "+departTime);
String dest=leg.get(l).getDestination();
System.out.println("Destination "+dest);
String destTer= leg.get(l).getDestinationTerminal();
System.out.println("DestTer "+destTer);
String origin=leg.get(l).getOrigin();
System.out.println("origun "+origin);
String originTer=leg.get(l).getOriginTerminal();
System.out.println("OriginTer "+originTer);
int durationLeg= leg.get(l).getDuration();
System.out.println("durationleg "+durationLeg);
int mil= leg.get(l).getMileage();
System.out.println("Milleage "+mil);
}
}
}
//Pricing
List<PricingInfo> priceInfo= tripResults.get(i).getPricing();
for(int p=0; p<priceInfo.size(); p++){
String price= priceInfo.get(p).getSaleTotal();
System.out.println("Price "+price);
}
}
return;
} catch (IOException e) {
System.err.println(e.getMessage());
} catch (Throwable t) {
t.printStackTrace();
}
System.exit(1);
}
}

Primavera API create udfcode local mode

Knows someone where I can find a sample of adding primavera UDF through API?
My code is below but nothing happens when I run it.
I can connect to the database, read the UDF, delete the udf, but not to create
Thank you
package apitest;
import com.primavera.bo.base.u;
import com.primavera.common.value.ObjectId;
import com.primavera.integration.client.*;
import com.primavera.integration.client.Session;
import com.primavera.integration.client.EnterpriseLoadManager;
import com.primavera.integration.client.RMIURL;
import com.primavera.integration.common.DatabaseInstance;
import com.primavera.integration.client.bo.BOIterator;
import com.primavera.integration.client.bo.object.Project;
import com.primavera.integration.client.bo.object.UDFCode;
import com.primavera.integration.client.bo.InternalBOHelper;
import com.primavera.integration.client.bo.helper.UDFCodeHelper;
public class API
{
public static void main( String[] args )
{
System.setProperty("primavera.bootstrap.home","C:\\P6IntegrationAPI_1");
Session session = null;
try
{
DatabaseInstance[] dbInstances = Session.getDatabaseInstances(
RMIURL.getRmiUrl( RMIURL.LOCAL_SERVICE ) );
// Assume only one database instance for now, and hardcode the username and
// password for this sample code
session = Session.login( RMIURL.getRmiUrl( RMIURL.LOCAL_SERVICE ),
dbInstances[0].getDatabaseId(), "admin", "admin" );
//u.delete(session, (UDFCode)(new String ("High")));
UDFCode u = new UDFCode(session);
u.setCodeValue("cdc");
u.setDescription("cdcds");
u.setObjectId(ObjectId.USESSION_OVERRIDE_ID);
u.setCodeTypeObjectId(ObjectId.USESSION_OVERRIDE_ID);
u.setSequenceNumber(0);
u.create();
System.out.println("cdcx");
}
catch ( Exception e )
{
System.out.println(e.getCause());
}
finally
{
if ( session != null )
session.logout();
}
}
}
A UDF Field in P6 is in fact 3 Types of Tables/Classes.
UdfType - is the type of UDF (Name, Datatype etc...)
UdfValue - this is the actual value u want to set i guess ?
UdfCodes - Thats UserDefined Codes so its a bit complex and is in fact a Code and no Field!
So if u want a simple UDF, just create a UdfType, this is part of the globaldata and must exists befor u add values. You can also add it over the client/web and fill it with values later.
Next try to insert some UdfValues on Activities. Thats the way i go every time ;)
Use the following template code to connect to the DB . Make sure you change bootstrap,username password values before using it.
import java.util.Date;
import java.util.Iterator;
import com.primavera.PrimaveraException;
import com.primavera.ServerException;
import com.primavera.bo.events.enm.SpreadPeriodType;
import com.primavera.common.value.Duration;
import com.primavera.common.value.ObjectId;
import com.primavera.common.value.spread.ActivitySpread;
import com.primavera.common.value.spread.ActivitySpreadPeriod;
import com.primavera.integration.client.GlobalObjectManager;
import com.primavera.integration.client.Session;
import com.primavera.integration.client.bo.BOIterator;
import com.primavera.integration.client.bo.BusinessObjectException;
import com.primavera.integration.client.bo.enm.ActivityStatus;
import com.primavera.integration.client.bo.enm.ProjectStatus;
import com.primavera.integration.client.bo.object.Activity;
import com.primavera.integration.client.bo.object.ActivityNote;
import com.primavera.integration.client.bo.object.EPS;
import com.primavera.integration.client.bo.object.NotebookTopic;
import com.primavera.integration.client.bo.object.Project;
import com.primavera.integration.client.bo.object.BaselineProject;
import com.primavera.integration.common.CopyActivityOptions;
import com.primavera.integration.common.CopyProjectOptions;
import com.primavera.integration.common.CopyWBSOptions;
import com.primavera.integration.common.DatabaseInstance;
import com.primavera.integration.client.bo.object.*;
import com.primavera.integration.client.*;
import com.primavera.integration.network.NetworkException;
import com.primavera.integration.*;
public class EPSFilter {
static Session session = null;
//static Session session = null;
private static final String PRIMAVERA_BOOTSTRAP_HOME = "primavera.bootstrap.home";
static final String PRIMAVERA_BOOTSTRAP_HOME_VALUE = "C:\\P6EPPM_832\\p6";
static final String PRIMAVERA_USERNAME = "admin";
static final String PRIMAVERA_PASSWORD = "admin";
static final String PRIMAVERA_SYSTEM = "pmdb832_n1";
static void openSession() throws PrimaveraException {
for (DatabaseInstance dbi : Session.getDatabaseInstances(null)) {
if (PRIMAVERA_SYSTEM.equalsIgnoreCase(dbi.getDatabaseName())) {
session = Session.login(null, dbi.getDatabaseId(), PRIMAVERA_USERNAME, PRIMAVERA_PASSWORD);
//session = Session.login (RMIURL.getRmiUrl( RMIURL.LOCAL_SERVICE ), "1", "admin", "admin");
System.out.println("Connected to Primavera instance " + PRIMAVERA_SYSTEM);
return;
}
}
throw new RuntimeException("Error, Primavera instance " + PRIMAVERA_SYSTEM + " not found");
}
public static void main(String[] args) throws BusinessObjectException, ServerException, NetworkException {
try {
System.setProperty(PRIMAVERA_BOOTSTRAP_HOME, PRIMAVERA_BOOTSTRAP_HOME_VALUE);
openSession();
} catch (PrimaveraException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Your code should follow to create the UDF's. If you still face issues. Please post the error you are getting

JUnit reporter does not show detailed report for each step in JBehave

I'm trying to set up JBehave for testing web services.
Template story is running well, but I can see in JUnit Panel only Acceptance suite class execution result. What I want is to see execution result for each story in suite and for each step in story like it is shown in simple JUnit tests or in Thucydides framework.
Here is my acceptance suite class: so maybe I Haven't configured something, or either I have to notate my step methods some other way, but I didn't find an answer yet.
package ***.qa_webservices_testing.jbehave;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;
import org.jbehave.core.Embeddable;
import org.jbehave.core.configuration.Configuration;
import org.jbehave.core.configuration.MostUsefulConfiguration;
import org.jbehave.core.io.CodeLocations;
import org.jbehave.core.io.LoadFromClasspath;
import org.jbehave.core.io.StoryFinder;
import org.jbehave.core.junit.JUnitStories;
import org.jbehave.core.parsers.RegexPrefixCapturingPatternParser;
import org.jbehave.core.reporters.CrossReference;
import org.jbehave.core.reporters.Format;
import org.jbehave.core.reporters.StoryReporterBuilder;
import org.jbehave.core.steps.InjectableStepsFactory;
import org.jbehave.core.steps.InstanceStepsFactory;
import org.jbehave.core.steps.ParameterConverters;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ***.qa_webservices_testing.jbehave.steps.actions.TestAction;
/**
* suite class.
*/
public class AcceptanceTestSuite extends JUnitStories {
private static final String CTC_STORIES_PATTERN = "ctc.stories";
private static final String STORY_BASE = "src/test/resources";
private static final String DEFAULT_STORY_NAME = "stories/**/*.story";
private static final Logger LOGGER = LoggerFactory.getLogger(AcceptanceTestSuite.class);
private final CrossReference xref = new CrossReference();
public AcceptanceTestSuite() {
configuredEmbedder()
.embedderControls()
.doGenerateViewAfterStories(true)
.doIgnoreFailureInStories(false)
.doIgnoreFailureInView(true)
.doVerboseFailures(true)
.useThreads(2)
.useStoryTimeoutInSecs(60);
}
#Override
public Configuration configuration() {
Class<? extends Embeddable> embeddableClass = this.getClass();
Properties viewResources = new Properties();
viewResources.put("decorateNonHtml", "true");
viewResources.put("reports", "ftl/jbehave-reports-with-totals.ftl");
// Start from default ParameterConverters instance
ParameterConverters parameterConverters = new ParameterConverters();
return new MostUsefulConfiguration()
.useStoryLoader(new LoadFromClasspath(embeddableClass))
.useStoryReporterBuilder(new StoryReporterBuilder()
.withCodeLocation(CodeLocations.codeLocationFromClass(embeddableClass))
.withDefaultFormats()
.withViewResources(viewResources)
.withFormats(Format.CONSOLE, Format.TXT, Format.HTML_TEMPLATE, Format.XML_TEMPLATE)
.withFailureTrace(true)
.withFailureTraceCompression(false)
.withMultiThreading(false)
.withCrossReference(xref))
.useParameterConverters(parameterConverters)
// use '%' instead of '$' to identify parameters
.useStepPatternParser(new RegexPrefixCapturingPatternParser(
"%"))
.useStepMonitor(xref.getStepMonitor());
}
#Override
protected List<String> storyPaths() {
String storiesPattern = System.getProperty(CTC_STORIES_PATTERN);
if (storiesPattern == null) {
storiesPattern = DEFAULT_STORY_NAME;
} else {
storiesPattern = "**/" + storiesPattern;
}
LOGGER.info("will search stories by pattern {}", storiesPattern);
List<String> result = new StoryFinder().findPaths(STORY_BASE, Arrays.asList(storiesPattern), Arrays.asList(""));
for (String item : result) {
LOGGER.info("story to be used: {}", item);
}
return result;
}
#Override
public InjectableStepsFactory stepsFactory() {
return new InstanceStepsFactory(configuration(), new TestAction());
}
}
my test methods look like:
Customer customer = new cutomer();
#Given ("I have Access to Server")
public void givenIHaveAccesToServer() {
customer.haveAccesToServer();
}
So they are notated only by JBehave notations.
The result returned in Junit panel is only like here (I yet have no rights to post images):
You should try this open source library:
https://github.com/codecentric/jbehave-junit-runner
It does exactly what you ask for :)
Yes, the codecentric runner works very nicely.
https://github.com/codecentric/jbehave-junit-runner