I want to create custom CronJob. I followed this tutorial, but unfortunately, I am not able to see my job instance in Backoffice.
*-item.xml
<typegroup name="Jobs">
<itemtype
generate="true"
code="UsersFindCronJob"
extends="CronJob"
jaloclass="de.hybris.training.core.jalo.UsersFindCronJob"
autocreate="true">
<attributes>
<attribute qualifier="firstName" type="java.lang.String">
<modifiers/>
<persistence type="property"/>
</attribute>
</attributes>
</itemtype>
</typegroup>
*spring.xml
<bean id="usersFindJob" class="de.hybris.training.core.job.UsersFindJob"
parent="abstractJobPerformable"/>
UsersFindJob.java
package de.hybris.training.core.job;
import de.hybris.platform.cronjob.enums.CronJobResult;
import de.hybris.platform.cronjob.enums.CronJobStatus;
import de.hybris.platform.servicelayer.cronjob.AbstractJobPerformable;
import de.hybris.platform.servicelayer.cronjob.PerformResult;
import de.hybris.training.core.model.UsersFindCronJobModel;
public class UsersFindJob extends AbstractJobPerformable<UsersFindCronJobModel> {
#Override
public PerformResult perform(UsersFindCronJobModel cronJobModel) {
try {
// Retrieve firstName from the cronJob
String firstName = cronJobModel.getFirstName();
// Display Hello firstName
System.out.println("Hello " + firstName);
// In case of success return result: SUCCESS and status: FINISHED
return new PerformResult(CronJobResult.SUCCESS, CronJobStatus.FINISHED);
} catch(Exception e) {
// In case of exception return result: ERROR and status: ABORTED
return new PerformResult(CronJobResult.ERROR, CronJobStatus.ABORTED);
}
}
}
Autogenerated UsersFindCronJobModel
/*
* ----------------------------------------------------------------
* --- WARNING: THIS FILE IS GENERATED AND WILL BE OVERWRITTEN! ---
* --- Generated at 09.Nis.2018 22:52:22 ---
* ----------------------------------------------------------------
*
* [y] hybris Platform
*
* Copyright (c) 2000-2016 SAP SE
* All rights reserved.
*
* This software is the confidential and proprietary information of SAP
* Hybris ("Confidential Information"). You shall not disclose such
* Confidential Information and shall use it only in accordance with the
* terms of the license agreement you entered into with SAP Hybris.
*
*/
package de.hybris.training.core.model;
import de.hybris.bootstrap.annotations.Accessor;
import de.hybris.platform.core.model.ItemModel;
import de.hybris.platform.cronjob.model.CronJobModel;
import de.hybris.platform.cronjob.model.JobModel;
import de.hybris.platform.servicelayer.model.ItemModelContext;
/**
* Generated model class for type UsersFindCronJob first defined at extension trainingcore.
*/
#SuppressWarnings("all")
public class UsersFindCronJobModel extends CronJobModel
{
/**<i>Generated model type code constant.</i>*/
public static final String _TYPECODE = "UsersFindCronJob";
/** <i>Generated constant</i> - Attribute key of <code>UsersFindCronJob.firstName</code> attribute defined at extension <code>trainingcore</code>. */
public static final String FIRSTNAME = "firstName";
/**
* <i>Generated constructor</i> - Default constructor for generic creation.
*/
public UsersFindCronJobModel()
{
super();
}
/**
* <i>Generated constructor</i> - Default constructor for creation with existing context
* #param ctx the model context to be injected, must not be null
*/
public UsersFindCronJobModel(final ItemModelContext ctx)
{
super(ctx);
}
/**
* <i>Generated constructor</i> - Constructor with all mandatory attributes.
* #deprecated since 4.1.1 Please use the default constructor without parameters
* #param _job initial attribute declared by type <code>CronJob</code> at extension <code>processing</code>
*/
#Deprecated
public UsersFindCronJobModel(final JobModel _job)
{
super();
setJob(_job);
}
/**
* <i>Generated constructor</i> - for all mandatory and initial attributes.
* #deprecated since 4.1.1 Please use the default constructor without parameters
* #param _job initial attribute declared by type <code>CronJob</code> at extension <code>processing</code>
* #param _owner initial attribute declared by type <code>Item</code> at extension <code>core</code>
*/
#Deprecated
public UsersFindCronJobModel(final JobModel _job, final ItemModel _owner)
{
super();
setJob(_job);
setOwner(_owner);
}
/**
* <i>Generated method</i> - Getter of the <code>UsersFindCronJob.firstName</code> attribute defined at extension <code>trainingcore</code>.
* #return the firstName
*/
#Accessor(qualifier = "firstName", type = Accessor.Type.GETTER)
public String getFirstName()
{
return getPersistenceContext().getPropertyValue(FIRSTNAME);
}
/**
* <i>Generated method</i> - Setter of <code>UsersFindCronJob.firstName</code> attribute defined at extension <code>trainingcore</code>.
*
* #param value the firstName
*/
#Accessor(qualifier = "firstName", type = Accessor.Type.SETTER)
public void setFirstName(final String value)
{
getPersistenceContext().setPropertyValue(FIRSTNAME, value);
}
}
Autogenerated GeneratedUsersFindCronJob
/*
* ----------------------------------------------------------------
* --- WARNING: THIS FILE IS GENERATED AND WILL BE OVERWRITTEN! ---
* --- Generated at 09.Nis.2018 22:52:22 ---
* ----------------------------------------------------------------
*
* [y] hybris Platform
*
* Copyright (c) 2000-2016 SAP SE
* All rights reserved.
*
* This software is the confidential and proprietary information of SAP
* Hybris ("Confidential Information"). You shall not disclose such
* Confidential Information and shall use it only in accordance with the
* terms of the license agreement you entered into with SAP Hybris.
*
*/
package de.hybris.training.core.jalo;
import de.hybris.platform.cronjob.jalo.CronJob;
import de.hybris.platform.jalo.Item.AttributeMode;
import de.hybris.platform.jalo.SessionContext;
import de.hybris.training.core.constants.TrainingCoreConstants;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
/**
* Generated class for type {#link de.hybris.training.core.jalo.UsersFindCronJob UsersFindCronJob}.
*/
#SuppressWarnings({"deprecation","unused","cast","PMD"})
public abstract class GeneratedUsersFindCronJob extends CronJob
{
/** Qualifier of the <code>UsersFindCronJob.firstName</code> attribute **/
public static final String FIRSTNAME = "firstName";
protected static final Map<String, AttributeMode> DEFAULT_INITIAL_ATTRIBUTES;
static
{
final Map<String, AttributeMode> tmp = new HashMap<String, AttributeMode>(CronJob.DEFAULT_INITIAL_ATTRIBUTES);
tmp.put(FIRSTNAME, AttributeMode.INITIAL);
DEFAULT_INITIAL_ATTRIBUTES = Collections.unmodifiableMap(tmp);
}
#Override
protected Map<String, AttributeMode> getDefaultAttributeModes()
{
return DEFAULT_INITIAL_ATTRIBUTES;
}
/**
* <i>Generated method</i> - Getter of the <code>UsersFindCronJob.firstName</code> attribute.
* #return the firstName
*/
public String getFirstName(final SessionContext ctx)
{
return (String)getProperty( ctx, FIRSTNAME);
}
/**
* <i>Generated method</i> - Getter of the <code>UsersFindCronJob.firstName</code> attribute.
* #return the firstName
*/
public String getFirstName()
{
return getFirstName( getSession().getSessionContext() );
}
/**
* <i>Generated method</i> - Setter of the <code>UsersFindCronJob.firstName</code> attribute.
* #param value the firstName
*/
public void setFirstName(final SessionContext ctx, final String value)
{
setProperty(ctx, FIRSTNAME,value);
}
/**
* <i>Generated method</i> - Setter of the <code>UsersFindCronJob.firstName</code> attribute.
* #param value the firstName
*/
public void setFirstName(final String value)
{
setFirstName( getSession().getSessionContext(), value );
}
}
Impex
INSERT_UPDATE UsersFindCronJob ; code[unique=true] ; job(code) ; firstName ; usersFindCronJob ; usersFindJob ; Mouad
I also tried to import that Impex but it said it is not valid.
I think you only missed to update your system. Then you can create the instance of your job using below Impex or through Backoffice.
To update
ant clean all
hybrisserver.bat
Open HAC (https://localhost:9002/hac/)
Go to Platform > Update
Only select Update running system checkbox and essential data of your extension.
If you are in the situation where you can't run essential data(say Production) you need to explicitly run ServiceLayerJob after the update.
Click on update button
Run Impex
INSERT_UPDATE UsersFindCronJob ; code[unique=true] ; job(code) ; firstName ;
; usersFindCronJob ; usersFindJob ; Mouad ;
The situation where you haven't run essential data you need to run below Impex(as mentioned by #Johannes)
INSERT_UPDATE ServicelayerJob;code[unique=true];springId;
;usersFindJob;usersFindJob
Refer https://wiki.hybris.com/display/R5T/Trail+~+CronJobs
First, you need to seperate your impex header from your data by a new line:
INSERT_UPDATE UsersFindCronJob;code[unique=true];job(code);firstName
;usersFindCronJob;usersFindJob;Mouad
Then you also missed the part where you create the Job itself:
INSERT_UPDATE ServicelayerJob;code[unique=true];springId;
;usersFindJob;usersFindJob
When you create your custom cronjob,then you need to update the "Custom Cronjob" you created.
****What mistake we do is updating these below statements when we write custom cronjob:****
INSERT_UPDATE ServicelayerJob;code[unique=true];springId;
INSERT_UPDATE Cronjob;code[unique=true];job(code);singleExecutable;sessionLanguage(isocode)
****Actually we need to write these below statements:****
INSERT_UPDATE ServicelayerJob;code[unique=true];springId;
INSERT_UPDATE ;code[unique=true];job(code);singleExecutable;sessionLanguage(isocode)
Please note that,if the attributes you added in custom cronjob are mandatory then you need to update those attributes as well,like:
INSERT_UPDATE ;code[unique=true];job(code);singleExecutable;sessionLanguage(isocode);
Related
I'm trying to get data for a new field added in login page. What I've done:
Modify AccountController.php login function adding new parameter: $this->_app->login($user, $client, !empty($data['rememberme']))
In Userfrosting.php login function i've set it in application: $this->client = $client;
In setupTwigUserVariables funtion added twig global: $twig->addGlobal("client", $this->client);
The problem is that in a template, {{client.id}} returns nothing. Any help will be appreciated.
In UserFrosting 4, you should create a Twig extension in your Sprinkle's src/Twig/ directory, and add the variable to the return value for getGlobals.
Your situation is a little tricky, since I'm not sure how client can be a global variable but at the same time depend on $data['client_id'] - which appears to be a request parameter. For now, I'll assume that you're submitting this parameter with any requests that require the client variable.
<?php
/**
* Stack Overflow
*
* #link https://stackoverflow.com
*/
namespace UserFrosting\Sprinkle\Site\Twig;
use Interop\Container\ContainerInterface;
use UserFrosting\Sprinkle\Site\Database\Models\Client;
/**
* Extends Twig functionality for the Site sprinkle.
*
* #author Jose Luis
*/
class Extension extends \Twig_Extension
{
protected $services;
protected $config;
public function __construct(ContainerInterface $services)
{
$this->services = $services;
$this->config = $services->config;
}
public function getName()
{
return 'myproject';
}
public function getGlobals()
{
try {
$currentUser = $this->services->currentUser;
// Assumes the client_id is being submitted as a query string (url) parameter
$clientId = $this->services->request->getQueryParam('client_id');
$client = Client::where('client_id', clientId)->where('userid', $currentUser->id)->first();
} catch (\Exception $e) {
$client = null;
}
return [
'client' => $client
];
}
}
You will then need to register this extension in your Sprinkle's service provider class:
<?php
/**
* Stack Overflow
*
* #link https://stackoverflow.com
*/
namespace UserFrosting\Sprinkle\Site\ServicesProvider;
use UserFrosting\Sprinkle\Site\Twig\Extension as JoseExtension;
/**
* Services provider for the Site sprinkle.
*
* #author Jose Luis
*/
class ServicesProvider
{
/**
* Register extended user fields services.
*
* #param Container $container A DI container implementing ArrayAccess and container-interop.
*/
public function register($container)
{
/**
* Extends the 'view' service with Jose's Twig Extension.
*/
$container->extend('view', function ($view, $c) {
$twig = $view->getEnvironment();
$extension = new JoseExtension($c);
$twig->addExtension($extension);
return $view;
});
}
}
Yes, I know that there is a lot of boilerplate here. However once you set these up the first time, it is easy to add new variables/functions/filters to the Twig environment and new services to your Sprinkle in the future.
I'm new to CXF and JAXB. I'm having problems with a RESTful client that calls a external web service. I think I've followed the steps necessary to do this but I'm getting the following error when executing the client:
SEVERE: No message body reader has been found for class com.jaxb.AcXML, ContentType: text/html
Exception in thread "main" javax.ws.rs.client.ResponseProcessingException: No message body reader has been found for class com.jaxb.AcXML, ContentType: text/html
at org.apache.cxf.jaxrs.impl.ResponseImpl.reportMessageHandlerProblem(ResponseImpl.java:433)
at org.apache.cxf.jaxrs.impl.ResponseImpl.doReadEntity(ResponseImpl.java:384)
at org.apache.cxf.jaxrs.client.AbstractClient.readBody(AbstractClient.java:512)
at org.apache.cxf.jaxrs.client.WebClient.handleResponse(WebClient.java:1173)
at org.apache.cxf.jaxrs.client.WebClient.doResponse(WebClient.java:1156)
at org.apache.cxf.jaxrs.client.WebClient.doChainedInvocation(WebClient.java:1092)
at org.apache.cxf.jaxrs.client.WebClient.doInvoke(WebClient.java:894)
at org.apache.cxf.jaxrs.client.WebClient.doInvoke(WebClient.java:865)
at org.apache.cxf.jaxrs.client.WebClient.invoke(WebClient.java:428)
at org.apache.cxf.jaxrs.client.WebClient.get(WebClient.java:611)
at com.ws.GetOpenPO.getOpenPOs(GetOpenPO.java:58)
at com.ws.GetOpenPO.main(GetOpenPO.java:79)
My IDE is Eclipse Indigo. I've created a Dynamic Web Project and included the CXF 2.x Web Services, JAX-RS and JAXB facets. Below is the class I'm testing with:
package com.ws;
import java.text.MessageFormat;
import javax.ws.rs.core.MediaType;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.cxf.transport.http.HTTPConduit;
import org.apache.cxf.transports.http.configuration.HTTPClientPolicy;
import com.jaxb.AcXML;
public class GetOpenPO {
private String baseUrl;
public AcXML getOpenPOs( )
{
// Create a WebClient pointing to the base URL of the RESTful web service
WebClient client = WebClient.create( baseUrl ).path("GetOpenPOs");
HTTPConduit http = WebClient.getConfig(client).getHttpConduit();
HTTPClientPolicy httpClientPolicy=new HTTPClientPolicy();
httpClientPolicy.setReceiveTimeout(1000000);
httpClientPolicy.setConnectionTimeout(1000000);
httpClientPolicy.setProxyServer("proxy1.global.mycompany.com");
httpClientPolicy.setProxyServerPort(8080);
http.setClient(httpClientPolicy);
// Set the path from which we wish to get the object, request XML, and use JAXB
AcXML POs= client.accept(MediaType.APPLICATION_XML)
.query("U", "parm1")
.query("P", "parm2")
.query("N", "parm3")
.query("Processed", "parm4")
.query("StationEnd", "")
.get( AcXML.class);
return POs;
}
public String getBaseUrl()
{
return baseUrl;
}
public void setBaseUrl( String baseUrl )
{
this.baseUrl = baseUrl;
}
public static void main(String args[]){
GetOpenPO x = new GetOpenPO ();
x.setBaseUrl("http://www24.externalws.net/webservices/webservices.asmx");
AcXML openPOs = x.getOpenPOs();
}
}
I was able to call the webservice via my browser, which returns an XML document. Using this XML I created a schema and then using the "JAXB Classes from Schema" wizard in Eclipse the JAXB objects were generated. Below is the source file for the AcXML entity that I'm trying to retrieve via the client:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2015.08.05 at 10:18:48 AM EDT
//
package com.jaxb;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element ref="{https://www.externalws.net/acXMLSchema.xsd}Header"/>
* <element ref="{https://www.externalws.net/acXMLSchema.xsd}Request"/>
* </sequence>
* <attribute name="lang" use="required">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema} string">
* </restriction>
* </simpleType>
* </attribute>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "", propOrder = {
"header",
"request"
})
#XmlRootElement(name = "acXML")
public class AcXML {
#XmlElement(name = "Header", required = true)
protected Header header;
#XmlElement(name = "Request", required = true)
protected Request request;
#XmlAttribute(name = "lang", required = true)
protected String lang;
/**
* Gets the value of the header property.
*
* #return
* possible object is
* {#link Header }
*
*/
public Header getHeader() {
return header;
}
/**
* Sets the value of the header property.
*
* #param value
* allowed object is
* {#link Header }
*
*/
public void setHeader(Header value) {
this.header = value;
}
/**
* Gets the value of the request property.
*
* #return
* possible object is
* {#link Request }
*
*/
public Request getRequest() {
return request;
}
/**
* Sets the value of the request property.
*
* #param value
* allowed object is
* {#link Request }
*
*/
public void setRequest(Request value) {
this.request = value;
}
/**
* Gets the value of the lang property.
*
* #return
* possible object is
* {#link String }
*
*/
public String getLang() {
return lang;
}
/**
* Sets the value of the lang property.
*
* #param value
* allowed object is
* {#link String }
*
*/
public void setLang(String value) {
this.lang = value;
}
}
Can someone tell me what I'm doing wrong or what am I missing that's causing the client to fail?
Thank You.
Add JAXBProvider
List<JAXBElementProvider> list = new ArrayList<JAXBElementProvider>();
list.add(new JAXBElementProvider());
WebClient client = WebClient.create( baseUrl, list).path("GetOpenPOs");
I'm trying to develop a project in Groovy and I've been looking through my code and trying to find areas which I could replace with something more idiomatically Groovy until I find a solution for another issue I've been having.
I've started taking a more in-depth look into the use of AST transformation annotations - they've helped significantly cut down on the amount of code I have to write in some places. However, I'm having an issue using the groovy.transform.builder.Builder annotation with one of my immutable value classes. The source for this annotation is hosted here.
The issue is that the annotation seems to make the builder set the values of the buildee directly rather than storing a copy of the values and passing them to the buildee's constructor. This results in a ReadOnlyPropertyException when you try to use it with immutable classes.
There are four possible Builder strategies you can select with this annotation, and of them I've tried DefaultStrategy, ExternalStrategy and InitializerStrategy. However, all of these have caused problems.
ExternalStrategy looks like the most promising of the four, and you can find an SSCCE based on it detailing the problem here.
The source code from the example is also included below:
import groovy.transform.Immutable
import groovy.transform.builder.Builder as GBuilder
import groovy.transform.builder.ExternalStrategy
/*
* Uncommenting the below causes a failure:
* 'groovy.lang.ReadOnlyPropertyException: Cannot set readonly property: value for class: Value'
*/
//#Immutable
class Value {
#GBuilder(forClass = Value, prefix = 'set', builderStrategy = ExternalStrategy)
static class Builder { }
int value
String toString() { "Value($value)" }
}
def builder = new Value.Builder()
println builder.setValue(1).build()
There also seems to be a relevant JIRA discussion on the matter here.
Edit
I've tried using CFrick's answer below, using InitializerStrategy rather than ExternalStrategy.
Everything now compiles, but I get the following errors at run-time when I try to execute my tests:
java.lang.IllegalAccessError: tried to access class com.github.tagc.semver.version.BaseVersion from class com.github.tagc.semver.version.BaseVersion$com.github.tagc.semver.version.BaseVersionInitializer
at java.lang.Class.getDeclaringClass(Class.java:1227)
at java.beans.MethodRef.set(MethodRef.java:46)
at java.beans.MethodDescriptor.setMethod(MethodDescriptor.java:117)
at java.beans.MethodDescriptor.<init>(MethodDescriptor.java:72)
at java.beans.MethodDescriptor.<init>(MethodDescriptor.java:56)
at java.beans.Introspector.getTargetMethodInfo(Introspector.java:1163)
at java.beans.Introspector.getBeanInfo(Introspector.java:426)
at java.beans.Introspector.getBeanInfo(Introspector.java:173)
at com.github.tagc.semver.version.VersionFactory.createBaseVersion(VersionFactory.groovy:34)
at com.github.tagc.semver.test.util.TestSetup.<clinit>(TestSetup.groovy:77)
at java.lang.Class.forName(Class.java:344)
at com.github.tagc.semver.version.SnapshotDecoratorSpec.#decoratedVersion should be considered equal to patch-bumped #releaseVersion snapshot(SnapshotDecoratorSpec.groovy:24)
Followed thereafter by a series of exceptions like the following:
java.lang.NoClassDefFoundError: Could not initialize class com.github.tagc.semver.test.util.TestSetup
at java.lang.Class.forName(Class.java:344)
at com.github.tagc.semver.version.SnapshotDecoratorSpec.#decoratedVersion should be considered equal to minor-bumped #releaseVersion snapshot(SnapshotDecoratorSpec.groovy:36)
What I have right now is a BaseVersion class like the following:
/**
* A concrete, base implementation of {#link com.github.tagc.semver.version.Version Version}.
*
* #author davidfallah
* #since v0.1.0
*/
#Immutable
#Builder(prefix = 'set', builderStrategy = InitializerStrategy)
#PackageScope
final class BaseVersion implements Version {
// ...
/**
* The major category of this version.
*/
int major = 0
/**
* The minor category of this version.
*/
int minor = 0
/**
* The patch category of this version.
*/
int patch = 0
/**
* Whether this version is a release or snapshot version.
*/
boolean release = false
// ...
}
A factory to produce instances of these:
/**
* A factory for producing base and decorated {#code Version} objects.
*
* #author davidfallah
* #since v0.5.0
*/
class VersionFactory {
// ...
/**
* Returns an instance of {#link com.github.tagc.semver.version.BaseVersion BaseVersion} constructed
* with the given parameters.
*
* #param major the major category value of the version instance
* #param minor the minor category value of the version instance
* #param patch the patch category value of the version instance
* #param release the release setting of the version instance
* #return an instance of {#code BaseVersion}
*/
static BaseVersion createBaseVersion(int major, int minor, int patch, boolean release) {
return new BaseVersion(major, minor, patch, release)
}
/**
* Returns an instance of {#link com.github.tagc.semver.version.BaseVersion BaseVersion} constructed
* with the given parameters.
*
* #param m a map of parameter names and their corresponding values corresponding to the
* construction parameters of {#code BaseVersion}.
*
* #return an instance of {#code BaseVersion}
*/
static BaseVersion createBaseVersion(Map m) {
return new BaseVersion(m)
}
/**
* Returns an instance of {#link com.github.tagc.semver.version.BaseVersion BaseVersion} constructed
* with the given parameters.
*
* #param l a list of parameter values corresponding to the construction parameters of {#code BaseVersion}.
*
* #return an instance of {#code BaseVersion}
*/
static BaseVersion createBaseVersion(List l) {
return new BaseVersion(l)
}
/**
* Returns a builder for {#link com.github.tagc.semver.version.BaseVersion BaseVersion} to specify
* the construction parameters for the {#code BaseVersion} incrementally.
*
* #return an instance of {#code BaseVersion.Builder}
*/
static Object createBaseVersionBuilder() {
return BaseVersion.builder()
}
// ...
}
A test specification class for Version objects:
/**
* Test specification for {#link com.github.tagc.semver.version.Version Version}.
*
* #author davidfallah
* #since 0.1.0
*/
#Unroll
class VersionSpec extends Specification {
static exampleVersions = [
VersionFactory.createBaseVersion(major:1, minor:2, patch:3),
VersionFactory.createBaseVersion(major:0, minor:0, patch:0),
VersionFactory.createBaseVersion(major:5, minor:4, patch:3),
VersionFactory.createBaseVersion(major:1, minor:16, patch:2),
VersionFactory.createBaseVersion(major:4, minor:5, patch:8),
]
// ...
}
And other classes that try to create instances of BaseVersion that are failing, such as TestSetup.
Your code there fails, because chosen strategy there basically does:
def v = new Value().with{ setValue(1); return it }
and this can not be done on #Immutable objects.
According to the docs, there is only InitializerStrategy, that can explicitly cope with #Immutable.
You can use the InitializerStrategy in conjunction with #Canonical and #Immutable. If your #Builder annotation doesn’t have explicit includes or excludes annotation attributes but your #Canonical annotation does, the ones from #Canonical will be re-used for #Builder.
E.g.
import groovy.transform.*
import groovy.transform.builder.*
#Immutable
#ToString
#Builder(prefix='set', builderStrategy=InitializerStrategy)
class Value {
int value
}
def builder = Value.createInitializer().setValue(1)
assert new Value(builder).toString()=='Value(1)'
Depending on what you are up to, this is rahter ugly syntax and you might be better off just using the Map-based c'tors. Even without e.g. #TypeChecked a new Value(vlaue: 666) will generate an error and leaving params (for a class with multiple properties) will leave them null.
How can I set the default value in field.
In my document I need to set default value false for field emailnotify
In mogodb th default value should be zero.
Check my document
namespace xxx\xxxBundle\Document;
use FOS\UserBundle\Document\User as BaseUser;
use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;
/**
* #MongoDB\Document
*/
class User extends BaseUser
{
/**
* #MongoDB\Id(strategy="auto")
*/
protected $id;
/**
* #MongoDB\Boolean
*/
protected $emailnotify;
/**
* Sets the emailnotify.
*
* #param boolean $emailnotify
*
* #return User
*/
public function setEmailnotify($emailnotify)
{
$this->emailnotify = (Boolean) $emailnotify;
return $this;
}
/**
* #return boolean
*/
public function isEmailnotify()
{
return $this->emailnotify;
}
}
I have found that setting the default value in the constructor works
public function __construct() {
$this->emailnotify = false;
}
Of course just setting the class variable to false will work for most parts if you use Doctrine to fetch the Document again afterwards, but the property will not be persisted to MongoDB like with the above.
I have tried to generate java classes from a schema xsd with JAXB2.1 and run XJC and it works.
I have included the schema in a wsdl file and i generate java classes with wsdl2java command using CXF.
The problem is abouta java class where there are difference:
The difference is the content attribute and its getter and setter which is missing with wsdl2java command.
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.1-b02-fcs
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
//
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.XmlValue;
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "BIN", **propOrder = {
"content"**
})
#XmlSeeAlso({
ED.class
})
public abstract class BIN {
**#XmlValue
protected String content;**
#XmlAttribute
protected BinaryDataEncoding representation;
/**
public String getContent() {
return content;
}
/**
*
* Binary data is a raw block of bits. Binary data is a
* protected type that MUST not be used outside the data
* type specification.
*
*
* #param value
* allowed object is
* {#link String }
*
*/
**public void setContent(String value) {
this.content = value;
}**
/**
* Gets the value of the representation property.
*
* #return
* possible object is
* {#link BinaryDataEncoding }
*
*/
public BinaryDataEncoding getRepresentation() {
if (representation == null) {
return BinaryDataEncoding.TXT;
} else {
return representation;
}
}
/**
* Sets the value of the representation property.
*
* #param value
* allowed object is
* {#link BinaryDataEncoding }
*
*/
public void setRepresentation(BinaryDataEncoding value) {
this.representation = value;
}
}
I need this attribute into this class.
Is there a way to do this like add a parameter?
This is my wsdl2java command:
call wsdl2java -Debug -verbose -exsh true -autoNameResolution -p %PACKAGE_BASE%.pa -p "urn:hl7-org:v3"=%PACKAGE_BASE%.patient.hl -d %PROJECT_HOME%\src\main\java\ %WSDL_HOME%\Test.wsdl
thanks