Java error incompatible types InputStream cannot be converted to Serializable - serializable

While using invoke method in oaf to call a method from AM i have an input stream variable to pass while using serializable to pass the parameters i'm facing an java error incompatible types saying input stream cannot be converted into serializable.Is there any other method to pass the values .Please help.Thanks.
try {
DataObject fileUploadData = pageContext.getNamedDataObject("Upload");
if (fileUploadData != null) {
String FileName = (String)fileUploadData.selectValue(null, "UPLOAD_FILE_NAME");
String contentType = (String)fileUploadData.selectValue(null, "UPLOAD_FILE_MIME_TYPE");
BlobDomain uploadedByteStream = (BlobDomain)fileUploadData.selectValue(null, FileName);
BoxDeveloperEditionAPIConnection api=(BoxDeveloperEditionAPIConnection)oam.invokeMethod("adminClient");
**Serializable parameters[]={entityName,key, FileName,uploadedByteStream.getInputStream(),api};** // Incompatible type error found for the last two values.Expecting serializable but found Input stream and api.
BoxFile.Info file = (BoxFile.Info)oam.invokeMethod("UploadFile",parameters);
return file;
} else {
pageContext.putDialogMessage(new OAException("Please choose the file", OAException.ERROR));
}
}

Related

How to read CSVRecord in apache beam?

I have a Java Iterable object, Iterable records. And I want to pass it to the Beam pipeline. I tried
PCollection csvRecordPC = p.apply("Create collection", Create.of(records));
It caused an error
An exception occured while executing the Java class. Can not determine a default Coder for a 'Create' PTransform that has no elements. Either add elements, call Create.empty(Coder), Create.empty(TypeDescriptor), or call 'withCoder(Coder)' or 'withType(TypeDescriptor)' on the PTransform.
Which Coder should I use? Or how can I write my custom coder?
I found a solution using FileIO.
p.apply(FileIO.match().filepattern(options.getInputFile()))
.apply(FileIO.readMatches())
.apply(ParDo.of(new CsvParser()))
The CsvPaser() is
public class CsvParser extends DoFn<ReadableFile, CSVRecord> {
#DoFn.ProcessElement
public void processElement(#Element ReadableFile element, DoFn.OutputReceiver<CSVRecord> receiver) throws IOException {
InputStream is = Channels.newInputStream(element.open());
Reader reader = new InputStreamReader(is);
Iterable<CSVRecord> records = CSVFormat.EXCEL.withFirstRecordAsHeader().parse(reader);
for (CSVRecord record : records) {
receiver.output(record);
}
}
}

Find Error When Using Codec

I have a simple object named Tag that has an id, name, and three numeric properties. I also have a codec for the object. The folloing code executes without error.
MongoDatabase tagsDatabase =
usersProcess.getMongoClient().getDatabase(tagsDB)
.withCodecRegistry(usersProcess.getCodecRegistry());
MongoCollection<Tag> tagsCollection =
tagsDatabase.getCollection(tagsCollectionName, Tag.class);
ArrayList<Tag> tagsList = new ArrayList<Tag>();
FindIterable<Tag> tagsByAlpha =
tagsCollection.find().sort(Sorts.ascending("name"));
Following this, the code
tagsByAlpha.forEach(new Consumer<Tag>() {
#Override
public void accept(Tag t) {
tagsList.add(t);
}
});
thows the exception "org.bson.BsonInvalidOperationException: readEndArray can only be called when ContextType is ARRAY, not when ContextType is DOCUMENT" at the first line (forEach). An alternative construct
MongoCursor<Tag> tagsCursor = tagsByAlpha.iterator();
throws the same exception. It seems to be implying that find() has returned Documents rather than Tag objects. At the same time, the code that does work suggests that what I'm trying is possible. What am I doing wrong?
Should have used org.bson.codecs.DoubleCodec

Jackson CSV Parser | Handle invalid values

I am trying to parse a CSV file which is feeded from upstream.
The CSV file contains some Date and Number fields for which format is pre decided. there are few instances where value in field is not as expected there we want to read those values as null but Jackson-CSV parser throws exception.
Below is My Excecption
at com.fasterxml.jackson.databind.exc.InvalidFormatException.from(InvalidFormatException.java:67)
at com.fasterxml.jackson.databind.DeserializationContext.weirdStringException(DeserializationContext.java:1535)
at com.fasterxml.jackson.databind.DeserializationContext.handleWeirdStringValue(DeserializationContext.java:910)
at com.fasterxml.jackson.databind.deser.std.StdDeserializer._parseDate(StdDeserializer.java:523)
at com.fasterxml.jackson.databind.deser.std.StdDeserializer._parseDate(StdDeserializer.java:466)
at com.fasterxml.jackson.databind.deser.std.DateDeserializers$DateBasedDeserializer._parseDate(DateDeserializers.java:195)
at com.fasterxml.jackson.databind.deser.std.DateDeserializers$DateDeserializer.deserialize(DateDeserializers.java:285)
at com.fasterxml.jackson.databind.deser.std.DateDeserializers$DateDeserializer.deserialize(DateDeserializers.java:268)
at com.fasterxml.jackson.databind.deser.impl.MethodProperty.deserializeAndSet(MethodProperty.java:127)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.vanillaDeserialize(BeanDeserializer.java:287)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:151)
at com.fasterxml.jackson.databind.MappingIterator.nextValue(MappingIterator.java:277)
I have reported the same on Jackson CSVGithub page too.
https://github.com/FasterXML/jackson-dataformat-csv/issues/153
You could try univocity-parsers as it can handle multiple formats in your date/number fields. For example:
public class MyClass {
#Format(formats = {"dd-MMM-yyyy", "yyyy-MM-dd"})
#Parsed
private Date date;
#Format(formats = {"$###,###.###", ""#0.00""})
#Parsed
private BigDecimal amount;
}
Now if no formats are compatible with what is coming for a giving input, you can handle the error with this:
CsvParserSettings settings = new CsvParserSettings();
settings.detectFormatAutomatically(); //no need to configure format or anything.
parserSettings.setProcessorErrorHandler(new RetryableErrorHandler<ParsingContext>() {
#Override
public void handleError(DataProcessingException error, Object[] inputRow, ParsingContext context) {
if(error.getColumnName().equals("date")){
//if there's an error in the date column, assign a default and proceed with the record.
setDefaultValue(new Date());
} else {
//else keep the record anyway. Null will be used instead of the value you can't process.
keepRecord(); //if you don't call keepRecord() the entire row is discarded.
}
}
});
Finally, you can parse your input with this:
List<MyClass> myClassList = new CsvRoutines(parserSettings).parseAll(MyClass.class, input);
Hope it helps.
Disclaimer: I'm the author of this library. It's open-source and free (Apache 2.0 license)

how to write multiple sets of data to a file using isolatedstoragefile

I have a listbox in my windows phone app and its datatemplate has 4 textbox controls in it to represent question,answer,date and emailid.
when user saves this data I want to save them to local storage so that I can read it later for displaying the same data in app.
So how to write multiple sets of data to a file using isolatedstoragefile with each set of data containing the above data(question,answer,date and emailed) in each row.
And while reading each record how do I read each column (question,answer,date and emailid)differently ? I know we can concatenate them while writing and split them while reading each line.But I want to know if there is a way provided in IsolatedstorageFile api to read the way I wanted above.
Just do like you would with a "normal" file.
I am not a big fan of a binary or XML serialization, so I would delimit the 4 fields with a semicolon and write each item (question;answer;date;emailid) on a new line. Save the resulting string into a file.
Then when reading, read the whole file into a string, split it by newline and you get all the items. For each line (item), split it using a semicolon and you get the 4 fields, you can cast them to the required types.
I use the Silverlight Serializer from http://whydoidoit.com/ and just serialize the object to isolated storage. Its a really good serializer - its fast and its files are small. The code used to save and retrieve is
public static void SaveFile(string filename, object serializableObject, Type type)
{
using (IsolatedStorageFile userStore = IsolatedStorageFile.GetUserStoreForApplication())
{
if (userStore.FileExists(filename))
{
userStore.DeleteFile(filename);
}
using (IsolatedStorageFileStream stream = userStore.CreateFile(filename))
{
SilverlightSerializer.Serialize(serializableObject, stream);
}
}
}
public static object LoadSerializedObjectFromFile(string filename, Type type)
{
using (IsolatedStorageFile userStore =
IsolatedStorageFile.GetUserStoreForApplication())
{
if (userStore.FileExists(filename))
{
using (IsolatedStorageFileStream stream = userStore.OpenFile(filename, FileMode.Open))
{
return SilverlightSerializer.Deserialize(stream);
}
}
}
return null;
}
I usually wrap the individual files in a repository (pattern). For instance in my Good Deal app, I have a DealRepository. In that repository I have a static Load method like shown here:
private static IDeal LoadRecentDeal()
{
IDeal savedDeals = IsolatedStorageHelper.LoadSerializedObjectFromFile(RecentDealFileName, typeof(Deal)) as Deal;
if (savedDeals != null)
{
return savedDeals;
}
else
{
return Deal.CreateNewDeal(RecentDealFileName);
}
}
The inner save method is something like this:
public void Save(IDeal deal)
{
deal.LastModifiedDate = DateTime.Now;
//
string fileName;
if (deal.Name == RecentDealFileName)
{
fileName = RecentDealFileName;
}
else
{
fileName = SavedDirectoryName + Path.DirectorySeparatorChar + deal.ID.ToString();
}
IsolatedStorageHelper.SaveFile(fileName, deal, typeof(IDeal));
}
And there are several other methods on the IsolatedStorageHelper and repositories used to do things like save a list of in multiple files and return them ... etc. All depends on your needs - but I would recommend checking out the Silverlight Serializer, it makes it pretty simple.

How to get TCM URI of multimedia type through file extension

I want to fetch the TCM URI of a multimedia type by passing file extension as parameter to method. Below is the code which I'm using but I getting some exception:-
private static string GetMultimediaTypeTCMURI(FileExtensionsList lFileExtensions)
{
string lTCMURI = "";
try
{
SessionAwareCoreService2010Client client
= new SessionAwareCoreService2010Client();
client.ClientCredentials.Windows.ClientCredential.UserName = "myUserName";
client.ClientCredentials.Windows.ClientCredential.Password = "myPassword";
client.Open();
FileExtensionsList list = new FileExtensionsList();
var mmType = client.GetSystemWideList(new MultimediaTypesFilterData())
.Single(mt => ((MultimediaTypeData)mt).FileExtensions == lFileExtensions);
lTCMURI = mmType.Id;
}
catch (Exception e)
{
throw new Exception("Please check either Mimetype"
+ lFileExtensions + "is wrong or Mimetype does not exist in SDL Tridion.");
}
return lTCMURI;
}
Call to above method:-
FileExtensionsList list = new FileExtensionsList();
list.Add("js");
GetMultimediaTypeTCMURI(list);
I'm getting "Sequence contains no matching element" exception with above code, anyone please suggest how to do this.
Sequence contains no matching element is thrown if there's no match to your Linq expression. What I see is that you are trying to match list of extensions:
mt => ((MultimediaTypeData)mt).FileExtensions == lFileExtensions
It means that file extensions of multimedia type should exactly match your lFileExtensions, it should even have the same order.
Instead, try searching by only 1 file extension you need:
mt => ((MultimediaTypeData)mt).FileExtensions.Contains(myFileExtension)
Consider also using SingleOrDefault method instead of Single. It will not throw exception, but return null if there's no match. You can later check multimedia type for null

Resources