I have a Jena model that I extract from a SPARQL CONSTRUCT, I want to translate it into JSON-LD, with the Embed feature, ie, if person1 knows person2, I want the person2 object inside person1, linked by the knows property.
Following examples around (1, 2), I've managed to do it through the setup of a context object:
Model m = SparqlUtils.construct ( sparql, model ); // yeah, I want JSON from a CONSTRUCT-extracted subgraph
StringWriter sw = new StringWriter ();
JsonLDWriteContext ctx = new JsonLDWriteContext ();
JsonLdOptions opts = new JsonLdOptions ();
opts.setEmbed ( "#always" );
ctx.setOptions ( opts );
Map<String, Object> frctx = new HashMap<> ( NamespaceUtils.getNamespaces () ); // this is just a map of prefix->uri
Map<String, String> knows = new HashMap<> ();
knows.put ( "#id", "foaf:knows" );
knows.put ( "#type", "#id" );
frctx.put ( "knows", knows );
frctx.put ( "name", "foaf:name" );
Map<String, Object> frame = new HashMap<> ();
frame.put ( "#type", "foaf:Person" );
frame.put ( "#context", frctx );
ctx.setFrame ( frame );
Graph graph = m.getGraph ();
PrefixMap prefixes = RiotLib.prefixMap ( graph );
WriterGraphRIOT writer = RDFDataMgr.createGraphWriter ( RDFFormat.JSONLD_FRAME_PRETTY );
writer.write ( sw, graph, prefixes, null, ctx );
However, I'm not happy at all with this solution, since I would be just fine with the default '#context', but if I don't set any frame into the ctx object that is passed to write(), I get an error that the context is missing. On the other hand, if I call write() with another format (eg, JSONLD_COMPACT_PRETTY), the ctx object seems to be ignored by the writer, ie, #embed = #always is ignored and the JSON I get is the usual list of flat objects, with the URIs as "knows" values.
How can I do it? Is there a way to get the default context? Is there a simpler way to tell about the embed option?
Related
How do I retrieve the first key from Gee.SortedMap in Vala?
For example if I have
Gee.SortedMap<int, string> foo = new Gee.TreeMap<int, string> ();
I want to get the first key, i.e. the lowest int in foo.
In Java we have java.util.SortedMap.firstKey(). I cannot find an equivalent in Vala.
The SortedMap has an ascending_keys property that returns a SortedSet. Then you can get the first() item from the SortedSet:
void main () {
Gee.SortedMap<int, string> foo = new Gee.TreeMap<int, string> ();
foo.set(2, "two");
foo.set(1, "one");
foo.set(0, "zero");
print(#"First sorted key: $(foo.ascending_keys.first())\n");
}
Is it possible to tell Tika or the parser that a ZIP can only contain files with a certain MimeType or file extension?
What iam currently use is the recursive parser to get all the information for every file.
final ParseContext context = new ParseContext();
final ContentHandlerFactory contentHandlerFactory = new BasicContentHandlerFactory( BasicContentHandlerFactory.HANDLER_TYPE.TEXT, -1 );
final RecursiveParserWrapperHandler recursiveParserWrapperHandler = new RecursiveParserWrapperHandler( contentHandlerFactory );
final RecursiveParserWrapper parser = new RecursiveParserWrapper( autoDetectParser );
context.set( Parser.class, parser );
parser.parse( tikaInputStream, recursiveParserWrapperHandler, metadata, context );
I am looking for a solution that the zip can only contain one file type and cannot contain any other zip/container. Currently I'm doing this by hand, but maybe there's a better solution. Especially with regard to zip bombing, another solution makes more sense.
final String contentType = metadata1.get( Metadata.CONTENT_TYPE );
final MediaType mediaType = MediaType.parse( contentType );
final MediaType expectedMediaType = MediaType.text( "turtle" );
final String depth = metadata1.get( TikaCoreProperties.EMBEDDED_DEPTH );
if ( MediaType.APPLICATION_ZIP.equals( mediaType ) ) {
if ( Integer.parseInt( depth ) > 0 ) {
throw new RuntimeException( "Not allowed depth path" );
}
return;
}
if ( !expectedMediaType.equals( mediaType ) ) {
throw new RuntimeException( "Not allowed media type" );
}
I added a own RecursiveParserWrapperHandler. Here is an example when the maximum embedded count is reached an exception is thrown.
public class ZipHandler extends RecursiveParserWrapperHandler {
private static final int MAX_EMBEDDED_ENTRIES = 10000;
public ZipHandler( final ContentHandlerFactory contentHandlerFactory ) {
super( contentHandlerFactory, MAX_EMBEDDED_ENTRIES );
}
#Override
public void endDocument( final ContentHandler contentHandler, final Metadata metadata ) throws SAXException {
if ( hasHitMaximumEmbeddedResources() ) {
throw new SAXException( "Max embedded entries reached: " + MAX_EMBEDDED_ENTRIES );
}
super.endDocument( contentHandler, metadata );
}
}
I have a problem with creating parent-child link in my TreeTable.
Setting of DataSource
table.setContainerDataSource(new TempPeopleContainer(((MyUI) UI.getCurrent()).peopleService.getItemList()));
table.setParent(1,0);
How can I set id of Object in this kind of DataSource setting? I've no explicit Id for elements of TreeTable.
Here is example from vaadin , where you can see "clearly" definition of Id's for each element (code not from my app):
TreeTable ttable = new TreeTable("My TreeTable");
ttable.addContainerProperty("Name", String.class, null);
ttable.addContainerProperty("Number", Integer.class, null);
ttable.setWidth("20em");
// Create the tree nodes and set the hierarchy
ttable.addItem(new Object[]{"Menu", null}, 0);
ttable.addItem(new Object[]{"Beverages", null}, 1);
ttable.setParent(1, 0);
ttable.addItem(new Object[]{"Foods", null}, 2);
ttable.setParent(2, 0);
it's my TempPeopleContainer class definition:
private class TempPeopleContainer extends FilterableListContainer<People> {
public TempPeopleContainer(final Collection<People> collection) {
super(collection);
}
// This is only temporarily overridden until issues with
// BeanComparator get resolved.
#Override
public void sort(final Object[] propertyId, final boolean[] ascending) {
final boolean sortAscending = ascending[0];
final Object sortContainerPropertyId = propertyId[0];
Collections.sort(getBackingList(), (o1, o2) -> {
int result = 0;
if ("lastname".equals(sortContainerPropertyId)) {
result = o1.getLastname().compareTo(o2.getLastname());
}
if (!sortAscending) {
result *= -1;
}
return result;
});
}
}
I hope my question is clear. Thanks.
It depends on your ItemContainer. The common BeanItemContainer from vaadin uses the item as item id itself as documented here https://vaadin.com/api/com/vaadin/data/util/BeanItemContainer.html
You are using vitrin's org.vaadin.viritin.ListContainer acting like the BeanItemContainer
So you could use the items from your list as itemId/newParentId if you want to stick at your ItemContainer implementations.
Or you could go the long way and get the item ids by iterating over com.vaadin.data.Container.getItemIds() and check manually if this item id is the parent id you want to use.
edit:
Try something like this:
List myList = ((MyUI) UI.getCurrent()).peopleService.getItemList();
TempPeopleContainer container = new TempPeopleContainer(myList);
table.setContainerDataSource(container);
table.setParent(myList.get(1), myList.get(0));
In the new Vaadin 7.4 release, the new Grid widget debuted as an alternative to the venerable Table.
After getting a Grid displayed, I later want to replace the entire set of data with fresh data. Rather than update the individual rows, I want to simply replace them.
I happen to be using a BeanItemContainer for easy read-only display of some objects with JavaBeans-style getter methods.
I considered two approaches:
Two step process of replacing bean items.
(1) First remove all BeanItem objects with Container::removeAllItems method.
(2) Then add replacement BeanItem objects with the BeanItemContainer::addAll method.
Replace entire BeanItemContainer.
Call Grid::setContainerDataSource and pass a new instance of BeanItemContainer constructed with fresh data.
Below is a sample application (Vaadin 7.4.2) showing both approaches. A pair of identical Grid widgets appear. Each has a button that updates data with either approach.
Results
The first approach (removing items and adding items) works. The fresh data immediately appears.
The second approach (replacing container rather than items) seems like it should work, with nothing contrary suggested in the scant documentation. But nothing happens. No exceptions or errors occur, yet no fresh data appears. I opened Ticket # 17268 on Vaadin trac for this issue.
Perhaps there are other better ways. Please post or comment with any alternatives.
Example App
Three classes are displayed below. You should be able to copy-paste into a new Vaadin 7.4.x app.
One class is the usual "MyUI" created in every new Vaadin app.
Another is simple JavaBeans-style class, "Astronomer", providing data for the rows in our Grid. That Astronomer class includes a convenient static method for generating a List of instances. Each new Astronomer gets a random number of popularity votes, to show fresh data values.
The meaty part of the example is in the "AstronomersLayout" class which creates the pair of Grids with their assigned buttons.
I use Java 8 Lambda syntax and the new java.time classes. So you may need to change your project's settings to use Java 8. In NetBeans 8 that means Project > Properties > Sources > Source/Binary Format (popup menu) > 1.8.
MyUI.java
Get your Vaadin app going.
package com.example.vaadingridexample;
import javax.servlet.annotation.WebServlet;
import com.vaadin.annotations.Theme;
import com.vaadin.annotations.VaadinServletConfiguration;
import com.vaadin.annotations.Widgetset;
import com.vaadin.server.VaadinRequest;
import com.vaadin.server.VaadinServlet;
import com.vaadin.ui.UI;
/**
* Example app in Vaadin 7.4.2 experimenting with two ways to replace data in a
* displayed Grid.
*
* #author Basil Bourque
*/
#Theme ( "mytheme" )
#Widgetset ( "com.example.vaadingridexample.MyAppWidgetset" )
public class MyUI extends UI
{
#Override
protected void init ( VaadinRequest vaadinRequest )
{
this.setContent( new AstronomersLayout() );
}
#WebServlet ( urlPatterns = "/*" , name = "MyUIServlet" , asyncSupported = true )
#VaadinServletConfiguration ( ui = MyUI.class , productionMode = false )
public static class MyUIServlet extends VaadinServlet
{
}
}
AstronomersLayout.java
The main part of the example.
package com.example.vaadingridexample;
import com.vaadin.data.util.BeanItemContainer;
import com.vaadin.shared.ui.grid.HeightMode;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Grid;
import com.vaadin.ui.VerticalLayout;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
/**
* Layout displays a pair of Grids, each with a Button to replace its contents
* with fresh data in either of two ways: (a) Replace all the items within the
* Container, or (b) Replace container itself.
*
* #author Basil Bourque
*/
#SuppressWarnings ( "serial" )
public class AstronomersLayout extends VerticalLayout
{
// -----| Member vars |--------------------------
Grid grid_ReplaceItems;
String gridCaption_ReplaceItems = "Astronomers - Replacing Items";
Button button_ReplaceItems;
Grid grid_ReplaceContainer;
String gridCaption_ReplaceContainer = "Astronomers - Replacing Container";
Button button_ReplaceContainer;
// -----| Constructor |--------------------------
public AstronomersLayout ()
{
this.prepareWidgets();
this.composeLayout();
}
// -----| Helper Methods |--------------------------
private void prepareWidgets ()
{
// Show updating a Grid by replacing the bean items within a container.
// Grid
List<Astronomer> listA = Astronomer.makeList();
BeanItemContainer<Astronomer> containerA = new BeanItemContainer<>( Astronomer.class , listA );
this.grid_ReplaceItems = new Grid( this.gridCaption_ReplaceItems , containerA );
//this.grid_ReplaceItems.setColumnOrder( "votes" , "givenName" , "surName" , "birthYear" );
this.grid_ReplaceItems.setColumnOrder( Astronomer.FIELD.VOTES.getName() , Astronomer.FIELD.GIVENNAME.getName() , Astronomer.FIELD.SURNAME.getName() , Astronomer.FIELD.BIRTHYEAR.getName() ); // Enum is a safer way of doing this: this.grid_ReplaceItems.setColumnOrder( "votes" , "givenName" , "surName" , "birthYear" );
this.grid_ReplaceItems.setHeightMode( HeightMode.ROW ); // Show all rows of data for this grid.
this.updateCaptionAndSize( this.grid_ReplaceItems , this.gridCaption_ReplaceItems );
// Button
this.button_ReplaceItems = new Button( "Replace Items" );
this.button_ReplaceItems.addClickListener( ( ClickEvent event ) -> {
#SuppressWarnings ( "unchecked" )
BeanItemContainer<Astronomer> bic = ( BeanItemContainer<Astronomer> ) this.grid_ReplaceItems.getContainerDataSource(); // Access existing container. Cast as need be.
bic.removeAllItems(); // Remove existing items.
bic.addAll( Astronomer.makeList() ); // Add fresh bean items to existing container.
this.updateCaptionAndSize( this.grid_ReplaceItems , this.gridCaption_ReplaceItems );
} );
// Show updating a Grid by replacing the container rather than its contents.
// Grid
List<Astronomer> listB = Astronomer.makeList();
BeanItemContainer<Astronomer> containerB = new BeanItemContainer<>( Astronomer.class , listB );
this.grid_ReplaceContainer = new Grid( this.gridCaption_ReplaceContainer , containerB );
this.grid_ReplaceContainer.setColumnOrder( Astronomer.FIELD.VOTES.getName() , Astronomer.FIELD.GIVENNAME.getName() , Astronomer.FIELD.SURNAME.getName() , Astronomer.FIELD.BIRTHYEAR.getName() );
this.grid_ReplaceContainer.setHeightMode( HeightMode.ROW ); // Show all rows of data for this grid.
this.updateCaptionAndSize( this.grid_ReplaceContainer , this.gridCaption_ReplaceContainer );
// Button
this.button_ReplaceContainer = new Button( "Replace Container" );
this.button_ReplaceContainer.addClickListener( ( ClickEvent event ) -> {
#SuppressWarnings ( "unchecked" )
BeanItemContainer<Astronomer> bic = new BeanItemContainer<>( Astronomer.class , listB ); // Create replacement container.
this.grid_ReplaceContainer.setContainerDataSource( bic );
this.updateCaptionAndSize( this.grid_ReplaceContainer , this.gridCaption_ReplaceContainer );
} );
}
private void updateCaptionAndSize ( final Grid grid , final String caption )
{
// Caption
grid.setCaption( caption + " ( updated " + this.now() + " )" ); // Update caption of Grid to indicate fresh data.
// Show all rows.
double h = grid.getContainerDataSource().size() > 0 ? grid.getContainerDataSource().size() : 3; // Cannot set height to zero rows. So if no data, set height to some arbitrary number of (empty) rows.
grid.setHeightByRows( h );
}
private void composeLayout ()
{
// Initialize this layout.
this.setMargin( true );
this.setSpacing( true );
// Content
this.addComponent( this.button_ReplaceItems );
this.addComponent( this.grid_ReplaceItems );
this.addComponent( this.button_ReplaceContainer );
this.addComponent( this.grid_ReplaceContainer );
}
// Helper method.
private String now ()
{
// Get current time in UTC. Truncate fractional seconds. Append a 'Z' to indicate UTC time zone.
return ZonedDateTime.now( ZoneOffset.UTC ).format( DateTimeFormatter.ISO_LOCAL_TIME ).substring( 0 , 8 ).concat( "Z" );
}
}
Astronomer.java
The data, the bean items, stored in a BeanItemContainer for display in a Grid.
A nested Enum provides a safer way to refer to the field names in the other class, AstronomersLayout for call to setColumnOrder.
package com.example.vaadingridexample;
import java.util.ArrayList;
import java.util.List;
/**
* Provides the beans to appear as rows in a BeanItemContainer backing a Grid.
*
* Note the static convenience method for generating a List of instances.
*
* #author Basil Bourque
*/
public class Astronomer
{
public enum FIELD
{
SURNAME( "surname" ),
GIVENNAME( "givenName" ),
BIRTHYEAR( "birthYear" ),
VOTES( "votes" );
private String name;
private FIELD ( String s )
{
this.name = s;
}
public String getName ()
{
return this.name;
}
}
// Members
private String surname;
private String givenName;
private Integer birthYear;
private Integer votes;
public Astronomer ( final String givenName , final String surName , final Integer birthYear )
{
this.surname = surName;
this.givenName = givenName;
this.birthYear = birthYear;
this.votes = this.random();
}
public static List<Astronomer> makeList ()
{
List<Astronomer> list = new ArrayList<>( 7 );
list.add( new Astronomer( "Hypatia" , "of Alexandria" , -370 ) );
list.add( new Astronomer( "Nicolaus" , "Copernicus" , 1473 ) );
list.add( new Astronomer( "Tycho" , "Brahe" , 1546 ) );
list.add( new Astronomer( "Giordano" , "Bruno" , 1548 ) );
list.add( new Astronomer( "Galileo" , "Galilei" , 1564 ) );
list.add( new Astronomer( "Johannes" , "Kepler" , 1571 ) );
list.add( new Astronomer( "Isaac" , "Newton" , 1643 ) );
list.add( new Astronomer( "Caroline" , "Herschel" , 1750 ) );
return list;
}
// ----| Helper Methods |----------------------------------
private Integer random ()
{
return ( int ) ( java.lang.Math.random() * 100 );
}
// ----| Bean Getters |----------------------------------
public String getSurname ()
{
return this.surname;
}
public String getGivenName ()
{
return this.givenName;
}
public Integer getBirthYear ()
{
return this.birthYear;
}
public Integer getVotes ()
{
return this.votes;
}
// ----| Object Superclass |----------------------------------
#Override
public String toString ()
{
return "Astronomer{ " + "surName=" + surname + " | givenName=" + givenName + " | birthYear=" + birthYear + " | votes=" + votes + " }";
}
}
You can simply get the record you have removed from button through clickListener with .getSelectedRow() .
After this you can remove your item from your grid with .removeItem().
IE:
Grid yourGrid = new Grid();
yourGrid.setContainerDataSource(yourData);
Button removeItem = new Button("Remove item");
removeItem.addClickListener(l -> {
Item selectedItem = (Item) yourGrid.getSelectedRow();
yourGrid.getContainerDataSource().removeItem(selectedItem);
});
Bye!
I want to put a generic POJO into ContentValues and unmarshall it within the ContentProvider.
I've been wracking my tiny brain re: Parcelables, ContentValues, and inserting into SQLite
Regarding:
http://njzk2.wordpress.com/2013/05/31/map-to-contentvalues-abusing-parcelable/
How to write a common code for inserting data in android's Sqlite
I've been trying to insert a android.location.Location into SQLite via ContentProvider:
Location loc = mLocationClient.getLastLocation();
myParcel = android.os.Parcel.obtain();
loc.writeToParcel(myParcel, 0);
ContentValues values = ContentValues.CREATOR.createFromParcel(myParcel );
to populate values w/ parcel.
Question 1)
Here is my ContentProvider.insert method:
#Override
public Uri insert( final Uri uri, final ContentValues values ){
SQLiteDatabase db = Mydatabase.getWritableDatabase();
//db.insert() doesn’t unmarshal the values??
db.insert( myTABLE_NAME, “”, values);
Uri result = null;
db.close();
return result;
}
this fails because the db.insert() doesn’t unmarshal the values (i believe)
Error inserting android.database.sqlite.SQLiteException: INSERT INTO myTABLE_NAME() VALUES (NULL)
Question 2)
Is there some way I can unmarshal values first and then marshal it back into another ContentValues variable? maybe w/ getKey()???
This works:
HashMap hm = new HashMap();
Location loc = mLocationClient.getLastLocation();
hm.put("LOCATIONS", loc);
android.os.Parcel myParcel = android.os.Parcel.obtain();
myParcel.writeMap(hm);
myParcel.setDataPosition(0);
ContentValues values = ContentValues.CREATOR.createFromParcel(myParcel);
getContentResolver().insert(MyUri, values);
and then
#Override
public Uri insert( final Uri uri, final ContentValues oldvalues ){
SQLiteDatabase db = GAELdatabase.getWritableDatabase();
Uri result = null;
Location loc = (Location)oldvalues.get("LOCATIONS");
ContentValues values = new ContentValues();
values.put("ALTITUDE", loc.getAltitude());//meters above sea level
values.put("LATITUDE", loc.getLatitude());
values.put("LONGITUDE", loc.getLongitude());
long rowID = db.insert( "MyTABLE_NAME", "", values);
db.close();
return result;
}