I get the following error trying to run my application
fatal error: use of unimplemented initializer 'init(entity:insertIntoManagedObjectContext:)' for class 'rcresttest.CatalogItem'
I can bypass this error by changing the Entity's class in the data model to something else, but then I will get a swift_dynamicCastClassUnconditional: when trying to downcast.
Is this a bug in beta6 or am I doing something wrong?
CatalogItem.swift
import CoreData
#objc(CatalogItem)
class CatalogItem : NSManagedObject {
#NSManaged var id : String
#NSManaged var slug : String
#NSManaged var catalogItemId : String
init(entity: NSEntityDescription!, context: NSManagedObjectContext!, catalogResultsDict : NSDictionary) {
super.init(entity: entity, insertIntoManagedObjectContext: context)
id = catalogResultsDict["Id"] as String
slug = catalogResultsDict["Slug"] as String
catalogItemId = catalogResultsDict["CatalogItemId"] as String
}
}
and the data model
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<model userDefinedModelVersionIdentifier="" type="com.apple.IDECoreDataModeler.DataModel" documentVersion="1.0" lastSavedToolsVersion="6220.8" systemVersion="13E28" minimumToolsVersion="Xcode 4.3" macOSVersion="Automatic" iOSVersion="Automatic">
<entity name="CatalogItem" representedClassName="CatalogItem" syncable="YES">
<attribute name="catalogItemId" optional="YES" attributeType="String" syncable="YES"/>
<attribute name="id" optional="YES" attributeType="String" syncable="YES"/>
<attribute name="slug" optional="YES" attributeType="String" syncable="YES"/>
</entity>
<elements>
<element name="CatalogItem" positionX="-45" positionY="0" width="128" height="90"/>
</elements>
</model>
Edit:
After changing the name of the datamodel class to have the module prefix The error message appears after trying to cast.
2014-08-20 10:49:15.335 rcresttest[63516:4194127] CoreData: warning: Unable to load class named 'rcresttest.CatalogItem' for entity 'CatalogItem'. Class not found, using default NSManagedObject instead.
This is a problem with the designated initializer. Just add convenience in front of your init and call init(entity:insertIntoManagedObjectContext:) on self instead super.
Related
I have a class OrderEntryData and inside I have an attribute which is a list of configurationInfoData (List< ConfigurationInfoData >) and inside this ConfigurationInfoData an attribute of Type Object (Object value).
This value will be sometime a date , a string or a customClass.
I am using Orika for the webServices and I am trying to settle the OrderEntryDTO class.
File : customcommerceWebServices-beans.xml
<bean class="de.hybris.platform.commercewebservicescommons.dto.order.ConfigurationInfoWsDTO">
<property name="label" type="java.lang.String" />
<property name="value" type="java.lang.Object" />
</bean>
<bean class="de.hybris.platform.commercewebservicescommons.dto.order.OrderEntryWsDTO">
<property name="configurationInfos" type="java.util.List<de.hybris.platform.commercewebservicescommons.dto.order.ConfigurationInfoWsDTO>" />
<property name="orderCode" type="java.lang.String" />
</bean>
I am testing with an Object which is an instance of AddressData.
Cause the Mapping/Conversion of the address object is working well
AddressData -> AddressDTO
the problem is (I think) Orika does not recognize the instance of the object (Object source) or the destination class (Object Target).
In the response I should have a AddressWsDTO but I get :
"de.hybris.platform.cmssmarteditwebservices.dto.AbstractPageWsDTO#54330c75"
I tried to implement a converter cause I was thinking maybe Orika don't Know how to convert an object to an AddressData (not working).
#WsDTOMapping
public class ScalpAddressConverter extends BidirectionalConverter<AddressData, Object> {
#Override
public Object convertTo(AddressData addressData, Type<Object> type, MappingContext mappingContext) {
return (Object) addressData;
}
#Override
public AddressData convertFrom(Object o, Type<AddressData> type, MappingContext mappingContext) {
return (AddressData) o;
}
}
I am having trouble passing enum value from Unity. This is my enum
public enum MyChoice
{
Choice1 = 1,
Choice2 = 2
}
I have registered typeAlias for this Enum Type like below.
<typeAlias alias ="MyChoice" type ="SomeNamespace.MyChoice, SomeAssembly" />
So far so good. Now, I need to pass an enum value to the constructor of a class from the configuration file. I am doing it as follows:
<register type="IMyInterface" mapTo="SomeClass" name="MyClass">
<constructor>
<param name ="choice" value="MyChoice.Choice1" />
</constructor>
</register>
I get an error MyChoice.Choice1 is not a valid value for MyChoice
Any idea ?
For it to work out of the box you should use the actual value for the enum and not the name. In this case instead of "MyChoice.Choice1" you should use "1".
If you want to use the name in the configuration (despite the posted example it is almost always more meaningful to use the enum name) then you could use a type converter.
Here's an example configuration:
<typeAlias alias ="EnumConverter" type ="SomeNamespace.EnumConverter`1, SomeAssembly" />
<register type="IMyInterface" mapTo="SomeClass" name="MyClass">
<constructor>
<param name ="choice" value="Choice1" typeConverter="EnumConverter[MyChoice]" />
</constructor>
</register>
And then create the EnumConverter:
public class EnumConverter<T> : System.ComponentModel.TypeConverter where T : struct
{
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
T result;
if (value == null || !Enum.TryParse<T>(value.ToString(), out result))
{
throw new NotSupportedException();
}
return result;
}
}
I have input complex big XML files for the Mule flow.
File end point-> Byte Array to String -> Splitter -> ....
I have got org.xml.sax.SAXParseException: Content is not allowed in prolog when I try to process input files by using Splitter component. When I create new XML file and copy content of original file to the file, input files are processed.
I delete BOM marker when I create new file. Original file has EF BB BF since the beginning of the file, local file has not.
Mule config:
<?xml version="1.0" encoding="UTF-8"?>
<mule xmlns:tracking="http://www.mulesoft.org/schema/mule/ee/tracking"
xmlns:mulexml="http://www.mulesoft.org/schema/mule/xml"
xmlns:doc="http://www.mulesoft.org/schema/mule/documentation"
xmlns:spring="http://www.springframework.org/schema/beans" version="EE-3.4.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.mulesoft.org/schema/mule/file
http://www.mulesoft.org/schema/mule/file/current/mule-file.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans
current.xsd
http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd
http://www.mulesoft.org/schema/mule/xml http://www.mulesoft.org/schema/mule/xml/current/mule-xml.xsd
http://www.mulesoft.org/schema/mule/ee/tracking
http://www.mulesoft.org/schema/mule/ee/tracking/current/mule-tracking-ee.xsd">
<mulexml:dom-to-xml-transformer name="domToXml"/>
<flow name="SplitterFlow1" doc:name="SplitterFlow1">
<file:inbound-endpoint path="D:\WORK\Input"
moveToDirectory="D:\WORK\Output"
responseTimeout="10000" doc:name="File" fileAge="200" encoding="UTF-8"/>
<byte-array-to-string-transformer doc:name="Byte Array to String" />
<splitter evaluator="xpath" expression="/Invoices/invoice"
doc:name="Splitter"/>
<transformer ref="domToXml" doc:name="Transformer Reference"/>
<tracking:custom-event event-name="Invoice ID" doc:name="Custom Business event">
</tracking:custom-event>
<logger level="INFO" doc:name="Logger"/>
<file:outbound-endpoint path="D:\WORK\Output"
outputPattern="#[function:dateStamp:dd-MM-yyyy-HH.mm.ss]-#[header:OUTBOUND:MULE_CORRELATION_SEQUENCE]"
responseTimeout="10000" doc:name="File"></file:outbound-endpoint>
</flow>
</mule>
Please advise me how I can do it in the Mule flow. Thank you in advance.
It's a pretty old post but here is my contribution.
Additionaly to the Java transformer approach suggested by #alexander-shapkin, I strongly recommend that you use Apache Commons' org.apache.commons.io.BOMInputStream to handle BOM marker out-of-the-box. The code would look something like below:
import java.io.InputStream;
import org.apache.commons.io.ByteOrderMark;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.input.BOMInputStream;
import org.mule.api.MuleMessage;
import org.mule.api.transformer.TransformerException;
import org.mule.transformer.AbstractMessageTransformer;
public class DeleteBOM extends AbstractMessageTransformer {
#Override
public Object transformMessage(MuleMessage message, String outputEncoding)
throws TransformerException {
try (InputStream in = new BOMInputStream(IOUtils.toInputStream(message.getPayloadAsString()), ByteOrderMark.UTF_8)) {
return IOUtils.toString(in);
} catch (Exception e) {
throw new RuntimeException("Could not remove BOM marker");
}
}
}
I partially reproduced your Mule app with the following configuration:
<file:connector name="File" autoDelete="false" streaming="true" validateConnections="true" doc:name="File" />
<mulexml:dom-to-xml-transformer name="DOM_to_XML" doc:name="DOM to XML"/>
<flow name="lalaFlow">
<file:inbound-endpoint path="D:\WORK\Input" moveToDirectory="D:\WORK\Output" responseTimeout="10000" doc:name="File" fileAge="200" encoding="UTF-8"/>
<component class="org.mule.bom.DeleteBOM" doc:name="Java"/>
<transformer ref="DOM_to_XML" doc:name="Transformer Reference"/>
...
</flow>
For further reference, go to https://commons.apache.org/proper/commons-io/javadocs/api-2.2/org/apache/commons/io/input/BOMInputStream.html
You can add before splitter an Java transformer with class:
package importxmltoapis;
import org.mule.api.MuleMessage;
import org.mule.api.transformer.TransformerException;
import org.mule.transformer.AbstractMessageTransformer;
public class DeleteBOM extends AbstractMessageTransformer{
public static final String BOM = "\uFEFF";
#Override
public Object transformMessage(MuleMessage message, String outputEncoding)
throws TransformerException {
String s="";
try {s = removeBOM(message.getPayloadAsString());} catch (Exception e) {e.printStackTrace();}
return s;
}
private static String removeBOM(String s) {
if (s.startsWith(BOM)) {
s = s.substring(1);
}
return s;
}
}
Try the following
1.Use the file to string transformer instead of bytearray to string transformer .
2.Check if you big xml is read completely and if not use the file age property of the file endpoint which will enable you to read your large file completely.
I am trying to execute following code but I am getting null pointer exception.
<property name="from" value="from"/>
<property name="to" value="to"/>
<taskdef name="groovy"
classname="org.codehaus.groovy.ant.Groovy"
classpath="G:\Tibco_Training\groovy-binary-1.8.5\groovy-all-1.6.5.jar" />
<taskdef resource="net/sf/antcontrib/antlib.xml"/>
<groovy>
class MoveDir extends org.apache.tools.ant.Task {
//def from = 'from'
//def to = 'to'
public void execute() {
new File(properties.from).eachFileMatch ~/.*/, { file ->
file.renameTo(new File(properties.to , file.getName()))
println "Moving file: $file.name from: " + from + " to: " + to }
}
}
project.addTaskDefinition('movedir', MoveDir)
</groovy>
<movedir />
If I don't use ant properties in groovy then the code works fine, but when I use ant properties for specifying directories, then it give null pointer exception. Am I passing wrong values or wrong syntax is the cause.
Wrong syntax, you have to use properties.'to' and properties.'from'
I have a problem with i18n enums in my JSF application. When I started, I had enums with the text defined inside. But now, I have keys tied to message bundles in the enum.
Example one of my enums:
public enum OrderStatus implements CustomEnum {
PENDING("enum.orderstatus.pending"),
CANCELED("enum.orderstatus.canceled");
/**
* key in message bundle
*/
private String name;
OrderStatus(String name) {
this.name = name;
}
#Override
public String getName() {
return name;
}
}
In the view layer, I use something like:
<!-- input -->
<h:selectOneMenu value="#{order.status}">
<f:selectItems value="#{flowUtils.orderStatuses}"/>
</h:selectOneMenu>
<!-- output -->
<h:outputText value="#{order.status}"/>
and in Java:
public class FlowUtils {
public List<SelectItem> getOrderStatuses() {
ArrayList<SelectItem> l = new ArrayList<SelectItem>();
for(OrderStatus c: OrderStatus.values()) {
// before i18n
// l.add(new SelectItem(c, c.getName()));
// after i18n
l.add(new SelectItem(c, FacesUtil.getMessageValue(c.getName())));
}
return l;
}
}
public class FacesUtil {
public static String getMessageValue(String name) {
FacesContext context = FacesContext.getCurrentInstance();
return context.getApplication().getResourceBundle(context, "m").getString(name);
}
}
It worked well, but when I needed to output #{order.status}, I needed to convert it.
So I implemented a converter, but got in trouble with conversion of String to Object in the getAsObject() method.
web.xml:
<converter>
<converter-for-class>model.helpers.OrderStatus</converter-for-class>
<converter-class>model.helpers.EnumTypeConverter</converter-class>
</converter>
Java:
public class EnumTypeConverter implements Converter {
#Override
public Object getAsObject(FacesContext context, UIComponent comp,
String value) throws ConverterException {
// value = localized value :(
Class enumType = comp.getValueBinding("value").getType(context);
return Enum.valueOf(enumType, value);
}
#Override
public String getAsString(FacesContext context, UIComponent component,
Object object) throws ConverterException {
if (object == null) {
return null;
}
CustomEnum type = (CustomEnum) object;
ResourceBundle messages = context.getApplication().getResourceBundle(context, "m");
String text = messages.getString(type.getName());
return text;
}
}
I'm entangled now with that. Anybody know how to internationalize multiple Enums efficiently?
The value which is passed through the converter is not the option label as you seem to expect, but the option value. The best practice is to not do this in the model side, but in the view side, because the model shouldn't need to be i18n aware.
As to the approach, you're basically unnecessarily overcomplicating things. Since JSF 1.2 there's a builtin EnumConverter which will kick in automatically and since JSF 2.0 you can iterate over a generic array or List in f:selectItems by the new var attribute without the need to duplicate the values over a List<SelectItem> in the model.
Here's how the bean can look like:
public class Bean {
private OrderStatus orderStatus;
private OrderStatus[] orderStatuses = OrderStatus.values();
// ...
}
And here's how the view can look like (assuming that msg refers to the <var> as you've definied in <resource-bundle> in faces-config.xml):
<h:selectOneMenu value="#{bean.orderStatus}">
<f:selectItems value="#{bean.orderStatuses}" var="orderStatus"
itemValue="#{orderStatus}" itemLabel="#{msg[orderStatus.name]}" />
</h:selectOneMenu>
That's all.
Unrelated to the problem, you've typos in the enum name and message keys, it should be:
PENDING("enum.orderstatus.pending"),
CANCELLED("enum.orderstatus.cancelled");
And, more clean would be to keep the bundle keys out the enum and use enum itself as part of bundle key. E.g.
PENDING,
CANCELLED;
<h:selectOneMenu value="#{bean.orderStatus}">
<f:selectItems value="#{bean.orderStatuses}" var="orderStatus"
itemValue="#{orderStatus}" itemLabel="#{msg['enum.orderstatus.' += orderStatus]}" />
</h:selectOneMenu>
enum.orderstatus.PENDING = Pending
enum.orderstatus.CANCELLED = Cancelled
I have posted my solution here: Internationalization of multiple enums (translation of enum values) - but still hoping for further enhancement.
EDIT: with the help of #Joop Eggen, we have come up with a really cool solution:
EDIT again: complete and ready-to-use solution:
Make a class
public final class EnumTranslator {
public static String getMessageKey(Enum<?> e) {
return e.getClass().getSimpleName() + '.' + e.name();
}
}
Make it a custom EL function
<?xml version="1.0" encoding="UTF-8"?>
<facelet-taglib
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facelettaglibrary_2_0.xsd"
version="2.0">
<namespace>http://example.com/enumi18n</namespace>
<function>
<function-name>xlate</function-name>
<function-class>your.package.EnumTranslator</function-class>
<function-signature>String getMessageKey(java.lang.Enum)</function-signature>
</function>
</facelet-taglib>
Add the taglib to your web.xml
<context-param>
<param-name>javax.faces.FACELETS_LIBRARIES</param-name>
<param-value>/WEB-INF/enumi18n.taglib.xml</param-value>
</context-param>
Have properties files enum_en.properties and enum_yourlanguage.properties like this
TransferStatus.NOT_TRANSFERRED = Not transferred
TransferStatus.TRANSFERRED = Transferred
Add the properties files as resource bundles to your faces-config.xml
<resource-bundle>
<base-name>kk.os.obj.jsf.i18n.enum</base-name>
<var>enum</var>
</resource-bundle>
Add the custom taglib to your xhtml files
<html ... xmlns:l="http://example.com/enumi18n">
And - voilĂ - you can now access the translated enum values in jsf:
<h:outputText value="#{enum[l:xlate(order.transferStatus)]}" />
Well, enum is just another class. There is nothing stopping you from adding parsing and to-string conversion methods that will parse and output locale-sensitive messages.
Maybe it violates Single Responsible Principle (does it?), but I believe making enum responsible for parsing and returning locale-aware values is the right thing to do.
Just add two methods like this:
public String toString(FacesContext context) {
// need to modify the method
FacesUtil.getMessageValue(context, name);
}
public OrderStatus parse(FacesContext context, String theName) {
for (OrderStatus value : values()) {
if (value.toString(context).equals(theName) {
return value;
}
}
// think of something better
return null;
}
I hope I got the code right, as I am not checking it with IDE now... Is this what you were looking for?
I calculate the message key in the enum like as shown below; so no need to maintain the keys with additional attributes on the enum
public String getMessageKey() {
return String.format("enum_%s_%s", this.getClass().getSimpleName(),
this.name());
}
Then I use it like this
<p:selectOneMenu id="type"
value="#{xyzBean.type}" required="true">
<f:selectItems
value="#{xyzBean.possibleTypes}"
var="type" itemLabel="#{msg[type.messageKey]}">
</f:selectItems>
</p:selectOneMenu>
with having configured a org.springframework.context.support.ReloadableResourceBundleMessageSource in the app context
<bean id="msg"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="/resources/locale/messages" />
<property name="useCodeAsDefaultMessage" value="true" />
<property name="cacheSeconds" value="1" />
</bean>
In case anyone is looking for a simple utility library to handle enum internationalization, please take a look at https://github.com/thiagowolff/litefaces-enum-i18n
The artifact is also available in Maven Central:
<dependency>
<groupId>br.com.litecode</groupId>
<artifactId>litefaces-enum-i18n</artifactId>
<version>1.0.1</version>
</dependency>
Basically, you just need to add the artifact to your project and define the enum respective keys following the described enum naming conventions. The translations (and also CSS class names) can be retrieved using the provided EL functions.