Can't load a service for category "ExternalGraphicFactory" - geotools

I'm using geotools-18.5, with JavaFx in Inteliji IDE.
When I want to create PointSymbolizer from a svg or png image.
StyleBuilder builder = new StyleBuilder();
ExternalGraphic extGraphic = builder.createExternalGraphic("file:/home/cuongnv/test.svg", "svg");
I build code OK, but when run, I received warning:
WARNING: Can't load a service for category "ExternalGraphicFactory".
Provider org.geotools.renderer.style.ImageGraphicFactory could not be
instantiated.
Can someone help me ?
Here is full code:
private Style createStyleBuilder(){
StyleBuilder builder = new StyleBuilder();
FilterFactory2 ff = builder.getFilterFactory();
// RULE 1
// first rule to draw cities
// define a point symbolizer representing a city
Graphic city = builder.createGraphic();
city.setSize(ff.literal(50));
ExternalGraphic extGraphic = builder.createExternalGraphic("file:/home/cuongnv/Javafx/GeoTool/geotools_fx_tutorial-master/geotools-fx/src/main/resources/images/console.svg", "svg"); // svg
city.addExternalGraphic(extGraphic);
PointSymbolizer pointSymbolizer = builder.createPointSymbolizer(city);
Rule rule1 = builder.createRule(pointSymbolizer);
rule1.setName("rule1");
rule1.getDescription().setTitle("City");
rule1.getDescription().setAbstract("Rule for drawing cities");
Rule rules[] = new Rule[] {rule1};
FeatureTypeStyle featureTypeStyle = builder.createFeatureTypeStyle("Feature", rules);
Style style = builder.createStyle();
style.setName("style");
style.getDescription().setTitle("User Style");
style.getDescription().setAbstract("Definition of Style");
style.featureTypeStyles().add(featureTypeStyle);
return style;
}
TYPE = DataUtilities.createType(
"Dataset",
"geometry:Geometry:srid=4326"
+ ","
+ "name:String,"
+ "id:String"
);
SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(TYPE);
GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory();
com.vividsolutions.jts.geom.Point point = geometryFactory.createPoint(new Coordinate(x,y));
featureBuilder.add(point);
SimpleFeature feature = featureBuilder.buildFeature(null);
DefaultFeatureCollection featureCollection = new DefaultFeatureCollection("internal", TYPE);
featureCollection.add(feature);
Style style = createStyleBuilder();
Layer layer = new FeatureLayer(featureCollection, style);
layer.setTitle("New Point");
mapContent.layers().add(layer);

You have set the image mime type incorrectly, it should be:
ExternalGraphic extGraphic = builder.createExternalGraphic("file:/stuff/ian/geoserver/data/styles/burg02.svg", "image/svg"); // svg
and all will work.
EDIT
If you are still having issues then try adding this code to the end of the createStyle module and look at the generated SVG, possibly in GeoServer to test it out.
SLDTransformer styleTransform = new SLDTransformer();
StyledLayerDescriptor sld = sf.createStyledLayerDescriptor();
UserLayer layer = sf.createUserLayer();
layer.setLayerFeatureConstraints(new FeatureTypeConstraint[] {null});
sld.addStyledLayer(layer);
layer.addUserStyle(style);
try {
String xml = styleTransform.transform(sld);
System.out.println(xml);
} catch (TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Related

How to Use Xamarin.Forms and GoogleMaps/GeoLocation

I am writing a Xamarin.Forms PCL app, to support iOS and Android OS for my app.
In the root project, I have a view containing a ViewList and a map (from Xamarin.Forms.Maps).
I learnt I have to use CustomRenderer for each platform to add customized behavior. What I am trying to achieve to add a LocationManager/GeoLocation to identify the users position via GPS and show his position with a pin/marker. Additionally to that, I get positions from the root project of several persons which pins must also be shown within the map.
Should I have to use an interface exporting functionality or use an appropriate custom map renderer?
I have no idea to achieve that, the examples at the Xamarin.Forms website and research within Stackoverflow do not give a hint.
Here is some code I have so far (extract):
using System;
using Awesome;
using Xamarin.Forms;
using Xamarin.Forms.Maps;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using Plugin.Geolocator;
using System.Threading.Tasks;
namespace KiLa
{
public class KidsFinder : ContentPage, ITabPage
{
public string TabIcon => FontAwesome.FAMapMarker;
public string SelectedTabIcon => FontAwesome.FAMapMarker;
private Boolean _showKidsList;
private ListView _listView;
public ObservableCollection<KidsViewModel> kidsList = new ObservableCollection<KidsViewModel>();
public KidsFinder ()
{
Title = "KidsFinder";
// Define listView
// Any near/identified kids? Mockup
// TODO: get real data
Boolean kidsPresent = true;
// Initial height of map
double mapHeight = 300.0;
// coordinates of Beuth Hochschule, Haus Gauss
double latitude = 52.543100;
double longitude = 13.351450;
// Show/hide kidsList (listView)
//Boolean showKidsList = false;
_showKidsList = false;
// Define toggleButton
Button toggleButton = new Button();
toggleButton.Text = "Verstecke Liste";
toggleButton.Clicked += new EventHandler(OnClickEvent);
if(kidsPresent == true)
{
toggleButton.IsVisible = true;
mapHeight = 200.0;
_showKidsList = true;
} else
{
toggleButton.IsVisible = false;
mapHeight = 300.0;
_showKidsList = false;
}
// Mockup some kids
Position pos1 = new Position(latitude + 0.002, longitude + 0.002);
Position pos2 = new Position (latitude - 0.002, longitude - 0.002);
kidsList.Add(new KidsViewModel{Name="Tim", ActualPositon=pos1, DistanceToEducator=5.4});
kidsList.Add(new KidsViewModel{Name="Sabine", ActualPositon=pos2, DistanceToEducator=20.4});
_listView = new ListView();
_listView.ItemsSource = kidsList;
//listView.VerticalOptions = LayoutOptions.FillAndExpand;
_listView.ItemTemplate = new DataTemplate (typeof(KidsCustomCell));
_listView.RowHeight = 50;
if (_showKidsList == false) {
_listView.IsVisible = false;
} else {
_listView.IsVisible = true;
}
// Define mapView
var kidsMap = new KidsMap ();
kidsMap.MapType = MapType.Street;
kidsMap.WidthRequest = 960;
kidsMap.HeightRequest = mapHeight;
kidsMap.MoveToRegion(MapSpan.FromCenterAndRadius(new Position(latitude,longitude), Distance.FromMiles(0.3)));
// Set label of pins with kids names,
foreach (KidsViewModel kvm in kidsList) {
Pin pin = new Pin() {
Label = kvm.Name,
Position = kvm.ActualPositon
};
kidsMap.Pins.Add(pin);
}
You should use GetLocation and declare the permissions necessary to use the LocationServices
[assembly: UsesPermission(Manifest.Permission.AccessFineLocation)]
[assembly: UsesPermission(Manifest.Permission.AccessCoarseLocation)]
This is not strictly necessary for obtaining the GPS coordinates of the device, but this example will attempt to provide a street address for the current location:
[assembly: UsesPermission(Manifest.Permission.Internet)]
Add a method called InitializeLocationManager to activity
void InitializeLocationManager()
{
_locationManager = (LocationManager) GetSystemService(LocationService);
Criteria criteriaForLocationService = new Criteria
{
Accuracy = Accuracy.Fine
};
IList<string> acceptableLocationProviders = _locationManager.GetProviders(criteriaForLocationService, true);
if (acceptableLocationProviders.Any())
{
_locationProvider = acceptableLocationProviders.First();
}
else
{
_locationProvider = string.Empty;
}
Log.Debug(TAG, "Using " + _locationProvider + ".");
}
The LocationManager class will listen for GPS updates from the device and notify the application by way of events. In this example we ask Android for the best location provider that matches a given set of Criteria and provide that provider to LocationManager.
For more details how to get current location using Xamarin Forms, follow this link: https://developer.xamarin.com/recipes/android/os_device_resources/gps/get_current_device_location/

How to get a Flag property from email message?

Can I somehow get a Flag property from EmailMessage or Item object? There is no getFlag() method, I also didn't find it in item.getPropertyBag(). I'm using ews-java-api-2.0. flag setting on outlook web app
There is a strongly type flag property in EWS in 2013 and greater so you could modify the EWS Java source to cater for that. Otherwise if you use the underlying Extended properties you can get the same information eg
ExtendedPropertyDefinition PR_FLAG_STATUS = new ExtendedPropertyDefinition(0x1090, MapiPropertyType.Integer);
ExtendedPropertyDefinition FlagRequest = new ExtendedPropertyDefinition(DefaultExtendedPropertySet.Common, 0x8530, MapiPropertyType.String);
PropertySet fiFindItemPropset = new PropertySet(BasePropertySet.FirstClassProperties);
fiFindItemPropset.Add(FlagRequest);
fiFindItemPropset.Add(PR_FLAG_STATUS);
FolderId FolderToAccess = new FolderId(WellKnownFolderName.Inbox, MailboxToAccess);
ItemView ivItemView = new ItemView(1000);
ivItemView.PropertySet = fiFindItemPropset;
FindItemsResults<Item> FindItemResults = null;
do
{
FindItemResults = service.FindItems(FolderToAccess, ivItemView);
foreach (Item itItem in FindItemResults.Items)
{
Console.WriteLine(itItem.Subject);
Object FlagValue = null;
if (itItem.TryGetProperty(FlagRequest, out FlagValue))
{
Console.WriteLine("Flag : " + FlagValue);
}
Object PR_FLAG_STATUS_Value = null;
if (itItem.TryGetProperty(PR_FLAG_STATUS, out PR_FLAG_STATUS_Value))
{
Console.WriteLine("PR_FLAG_STATUS : " + PR_FLAG_STATUS_Value);
}
}
ivItemView.Offset += FindItemResults.Items.Count;
} while (FindItemResults.MoreAvailable);
Theres a full list of flag properties https://msdn.microsoft.com/en-us/library/ee201258(v=exchg.80).aspx

Xamarin free HTML or DOC to PDF Conversion

I'm currently searching for a library or a way to convert HTML OR DOCX files into PDF on the phone/tab, primarily I'am searching for a way on Android or iOS idk if its a PCL or platform specific approach. I could do this for every Platform independently, because our app requires iOS 8 or android kitkat, both supporting native PDF conversion but i want to do it seamless for the user, so the question is, if anyone has done this before, without loading it into a visible Webview at first or has knowledge of an open not GPL licensed API(can't publish the code), to do this with Xamarin.
I am aware of the possibility to do this online, but I don't want to to be dependent to a online service for this.
Help and ideas are appreciated.
Android Solution:
Call the SafeHTMLToPDF(string html, string filename) via a dependency service like
DependencyService.Get<YOURINTERFACE>().SafeHTMLToPDF(htmlString, "Invoice");
public string SafeHTMLToPDF(string html, string filename)
{
var dir = new Java.IO.File(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath + "/pay&go/");
var file = new Java.IO.File(dir + "/" + filename + ".pdf");
if (!dir.Exists())
dir.Mkdirs();
int x = 0;
while (file.Exists())
{
x++;
file= new Java.IO.File(dir + "/" + filename + "( " + x + " )" + ".pdf");
}
if (webpage == null)
webpage = new Android.Webkit.WebView(GetApplicationContext());
int width = 2102;
int height = 2973;
webpage.Layout(0, 0, width, height);
webpage.LoadDataWithBaseURL("",html, "text/html", "UTF-8" , null);
webpage.SetWebViewClient(new WebViewCallBack(file.ToString()));
return file.ToString();
}
class WebViewCallBack : WebViewClient
{
string fileNameWithPath = null;
public WebViewCallBack(string path)
{
this.fileNameWithPath = path;
}
public override void OnPageFinished(Android.Webkit.WebView myWebview, string url)
{
PdfDocument document = new PdfDocument();
PdfDocument.Page page = document.StartPage(new PdfDocument.PageInfo.Builder(2120 ,3000, 1).Create());
myWebview.Draw(page.Canvas);
document.FinishPage(page);
Stream filestream = new MemoryStream();
FileOutputStream fos = new Java.IO.FileOutputStream(fileNameWithPath, false); ;
try
{
document.WriteTo(filestream);
fos.Write(((MemoryStream)filestream).ToArray(), 0, (int)filestream.Length);
fos.Close();
}
catch
{
}
}
}
And the Way to do it under iOS
public string SafeHTMLToPDF(string html, string filename)
{
UIWebView webView = new UIWebView(new CGRect(0, 0, 6.5 * 72, 9 * 72));
var documents = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
var file = Path.Combine(documents, "Invoice" + "_" + DateTime.Now.ToShortDateString() + "_" + DateTime.Now.ToShortTimeString() + ".pdf");
webView.Delegate = new WebViewCallBack(file);
webView.ScalesPageToFit = true;
webView.UserInteractionEnabled = false;
webView.BackgroundColor = UIColor.White;
webView.LoadHtmlString(html, null);
return file;
}
class WebViewCallBack : UIWebViewDelegate
{
string filename = null;
public WebViewCallBack(string path)
{
this.filename = path;
}
public override void LoadingFinished(UIWebView webView)
{
double height, width;
int header, sidespace;
width = 595.2;
height = 841.8;
header = 10;
sidespace = 10;
UIEdgeInsets pageMargins = new UIEdgeInsets(header, sidespace, header, sidespace);
webView.ViewPrintFormatter.ContentInsets = pageMargins;
UIPrintPageRenderer renderer = new UIPrintPageRenderer();
renderer.AddPrintFormatter(webView.ViewPrintFormatter, 0);
CGSize pageSize = new CGSize(width, height);
CGRect printableRect = new CGRect(sidespace,
header,
pageSize.Width - (sidespace * 2),
pageSize.Height - (header * 2));
CGRect paperRect = new CGRect(0, 0, width, height);
renderer.SetValueForKey(NSValue.FromObject(paperRect), (NSString)"paperRect");
renderer.SetValueForKey(NSValue.FromObject(printableRect), (NSString)"printableRect");
NSData file = PrintToPDFWithRenderer(renderer, paperRect);
File.WriteAllBytes(filename, file.ToArray());
}
private NSData PrintToPDFWithRenderer(UIPrintPageRenderer renderer, CGRect paperRect)
{
NSMutableData pdfData = new NSMutableData();
UIGraphics.BeginPDFContext(pdfData, paperRect, null);
renderer.PrepareForDrawingPages(new NSRange(0, renderer.NumberOfPages));
CGRect bounds = UIGraphics.PDFContextBounds;
for (int i = 0; i < renderer.NumberOfPages; i++)
{
UIGraphics.BeginPDFPage();
renderer.DrawPage(i, paperRect);
}
UIGraphics.EndPDFContent();
return pdfData;
}
}
Frustrated with the existing solutions, I've built some extension methods (OpenSource, MIT Licensed) that convert HTML or the content of a Xamarin.Forms.WebView to a PDF file. Sample usage for WebView to PDF:
async void ShareButton_Clicked(object sender, EventArgs e)
{
if (Forms9Patch.ToPdfService.IsAvailable)
{
if (await webView.ToPdfAsync("output.pdf") is ToFileResult pdfResult)
{
if (pdfResult.IsError)
using (Toast.Create("PDF Failure", pdfResult.Result)) { }
else
{
var collection = new Forms9Patch.MimeItemCollection();
collection.AddBytesFromFile("application/pdf", pdfResult.Result);
Forms9Patch.Sharing.Share(collection, shareButton);
}
}
}
else
using (Toast.Create(null, "PDF Export is not available on this device")) { }
}
}
For a more complete explanation of how to use it, here's a short article: https://medium.com/#ben_12456/share-xamarin-forms-webview-as-a-pdf-a877542e824a?
You can able to convert the HTML to PDF file without any third party library. I am sharing my git repo for future reference.
https://github.com/dinesh4official/XFPDF
Yes, you can convert a Word document to PDF in Xamarin with a few lines of code easily. You need to refer Syncfusion.Xamarin.DocIORenderer from nuget.org
Assembly assembly = typeof(App).GetTypeInfo().Assembly;
// Retrieves the document stream from embedded Word document
Stream inputStream = assembly.GetManifestResourceStream("WordToPDF.Assets.GettingStarted.docx");
string fileName = "GettingStarted.pdf";
// Creates new instance of WordDocument
WordDocument wordDocument = new WordDocument(inputStream,Syncfusion.DocIO.FormatType.Automatic);
inputStream.Dispose();
// Creates new instance of DocIORenderer for Word to PDF conversion
DocIORenderer render = new DocIORenderer();
// Converts Word document into PDF document
PdfDocument pdfDocument = render.ConvertToPDF(wordDocument);
// Releases all resources used by the DocIORenderer and WordDocument instance
render.Dispose();
document.Close();
// Saves the converted PDF file
MemoryStream outputStream = new MemoryStream();
pdfDocument.Save(outputStream);
// Releases all resources used by the PdfDocument instance
pdfDocument.Close();
To know more about this, kindly refer here.

How to get byteArray or base64 string from RenderTexture Cocos2d-JS

I am making a game on cocos2d-JS for facebook in which there is a requirement of sharing a screenshot of the game.
I am able to take the screenshot but now I am unable to upload it in the Parse.com server because it requires base64 format or byte array. I am unable to find any solution of converting Sprite in to this format.. Here's my code so result when I do addchild its coming proper .. I have also added my commented code so that it will help to understand that I have tried lot of things but couldnt achieve the same.
shareToSocialNetworking: function () {
cc.director.setNextDeltaTimeZero(true);
var newsize = cc.director.getVisibleSize();
var renderText = new cc.RenderTexture(newsize.width,newsize.height);
renderText.begin();
cc.director.getRunningScene().visit();
renderText.end();
var result = cc.Sprite.create(renderText.getSprite().getTexture());
result.flippedY = true;
this._mainViewNode.addChild(result,6000);
//renderText.saveToFile("screenshot.jpg",cc.IMAGE_FORMAT_PNG);
//var based = renderText.getSprite().getTexture().getStringForFormat().toString();
//var data = based.getData();
var file = new Parse.File("screen.jpg", { base64: this.getBase64(result) });
//var file = new Parse.File("screen.jpg", data, "image/png");
var self = this;
file.save().then(function() {
// The file has been saved to Parse.
alert(file.url);
this.onSharePictureInfoLink(file.url());
}, function(error) {
// The file either could not be read, or could not be saved to Parse.
});
//
//var ccImage = renderText.newCCImage();
//
//var str = ccImage.getData();
},
is there any workaround that can be done
there is a private variable called _cacheCanvas, which is the instance of the offscreen canvas
you can simply do renderText._cacheCanvas.toDataURL()
Here's how you can take the screnshot from cocos2d-JS
screenshot: function (fileName) {
var tex = new cc.RenderTexture(winSize.width, winSize.height, cc.Texture2D.PIXEL_FORMAT_RGBA8888);
tex.setPosition(cc.p(winSize.width / 2, winSize.height / 2));
tex.begin();
cc.director.getRunningScene().visit();
tex.end();
var imgPath = jsb.fileUtils.getWritablePath();
if (imgPath.length == 0) {
return;
}
var result = tex.saveToFile(fileName, cc.IMAGE_FORMAT_JPEG);
if (result) {
imgPath += fileName;
cc.log("save image:" + imgPath);
return imgPath;
}
return "";
}
then make a Java call from Javascript
public static void ScreenShot()
{
Bitmap imageBitmap = BitmapFactory.decodeFile(Cocos2dxHelper.getCocos2dxWritablePath() + "/" + "screenshot.png");
String fileHolder = "SampleFolder";
File filepathData = new File("/sdcard/" + fileHolder);
//~~~Create Dir
try {
if (!filepathData.exists())
{
filepathData.mkdirs();
filepathData.createNewFile();
FileWriter fw = new FileWriter(filepathData + fileHolder);
BufferedWriter out = new BufferedWriter(fw);
String toSave = String.valueOf(0);
out.write(toSave);
out.close();
}
}
catch (IOException e1) {
}
//~~~Create Image
File file = new File("/sdcard/" + "Your filename");
try
{
file.createNewFile();
FileOutputStream ostream = new FileOutputStream(file);
imageBitmap.compress(CompressFormat.PNG, 100, ostream);
ostream.close();
}
catch (Exception e) {}
Uri phototUri = Uri.fromFile(file);
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, phototUri);
//~~~Add Code Below
}
Do not forget to add permission for external storage

AS3 load variables from a txt file which has && formatting

I'm trying to load a txt file of variables into my AS3 project. The problem I have though seems to be down to the fact that the txt file (which is pre formatted and cannot be changed) is formatted using double amphersands... e.g.
&name=mark&
&address=here&
&tel=12345&
I'm using the following code to load the txt file
myLoader.addEventListener(Event.COMPLETE, onLoaded, false, 0, true);
myLoader.dataFormat = URLLoaderDataFormat.VARIABLES;
urlRqSend = new URLRequest(addressToTxt.txt);
public function onLoaded(e:Event):void {
trace(myLoader.data);
}
Using URLLoaderDataFormat.VARIABLES generates the following error:
Error: Error #2101: The String passed to URLVariables.decode() must be a URL-encoded query string containing name/value pairs.
If I use URLLoaderDataFormat.TEXT I can load the data successfully but I'm not able (or don't know how to) access the variables.
Would anyone have any ideas or work arounds to this please.
Thanks,
Mark
I had that kind of problem some time ago.
I suggest you to load first as a text, remove those line breaks, the extra amphersands and parse manually:
var textVariables:String;
var objectVariables:Object = new Object();
...
myLoader.addEventListener(Event.COMPLETE, onLoaded, false, 0, true);
myLoader.dataFormat = URLLoaderDataFormat.TEXT;
urlRqSend = new URLRequest(addressToTxt.txt);
public function onLoaded(e:Event):void {
textVariables = myLoader.data;
textVariables = textVariables.split("\n").join("").split("\r").join(""); // removing line breaks
textVariables = textVariables.split("&&").join("&"); // removing extra amphersands
var params:Array = textVariables.split('&');
for(var i:int=0, index=-1; i < params.length; i++)
{
var keyValuePair:String = params[i];
if((index = keyValuePair.indexOf("=")) > 0)
{
var key:String = keyValuePair.substring(0,index);
var value:String = keyValuePair.substring(index+1);
objectVariables[key] = value;
trace("[", key ,"] = ", value);
}
}
}
I wrote that code directly here, I don't have any AS3 editor here, so, maybe you'll find errors.
If you have data in String and it has a structure just like you wrote, you can do a workaround:
dataInString = dataInString.split("\n").join("").split("\r").join(""); // removing EOL
dataInString = dataInString.slice(0,-1); // removing last "&"
dataInString = dataInString.slice(0,1); // removing first "&"
var array:Array = dataInString.split("&&");
var myVariables:Object = new Object();
for each(var item:String in array) {
var pair:Array = item.split("=");
myVariables[pair[0]] = pair[1];
}
That should make you an object with proper variables.