How to read WMS using GDAL Java Bindings OpenEX? - geospatial

I would like to read Raster tiles from a WMS endpoint. The endpoint has UN and PW authentication.
I am using the GDAL Java bindings, and I'm getting a 401 on my request.
I don't know the convention for putting the UN and PW into the options, or I am missing something completely. I'm new to GDAL.
Here is my code
public class WMS {
static {
gdal.AllRegister();
System.out.println("registered GDAL");
}
public static void main(String[] args) {
Vector options = new Vector();
options.add(0,"some UN");//????
options.add(1,"some PW");//???
Dataset d = gdal.OpenEx("https://some/wms/",1L,new Vector(), options);
}
}

Related

Azure Cognitive Service\Computer Visio\OCR - Can I use it into into WebSite C#

I'm trying to use Azure Ocr into my website c#.
I added the package Microsoft.Azure.CognitiveServices.Vision.ComputerVision and I wrote code, with key and endpoint of my subscription.
static string subscriptionKey = "mykey";
static string endpoint = "https://myocr.cognitiveservices.azure.com/";
private const string ANALYZE_URL_IMAGE = "https://raw.githubusercontent.com/Azure-Samples/cognitive-services-sample-data-files/master/ComputerVision/Images/printed_text.jpg";
protected void Page_Load(object sender, EventArgs e)
{
// Create a client
ComputerVisionClient client = Authenticate(endpoint, subscriptionKey);
// Analyze an image to get features and other properties.
AnalyzeImageUrl(client, ANALYZE_URL_IMAGE).Wait();
}
public static ComputerVisionClient Authenticate(string endpoint, string key)
{
ComputerVisionClient client =
new ComputerVisionClient(new ApiKeyServiceClientCredentials(key))
{ Endpoint = endpoint };
return client;
}
public static async Task AnalyzeImageUrl(ComputerVisionClient client, string imageUrl)
{
// Read text from URL
var textHeaders = await client.ReadAsync(imageUrl);
...
}
It seems all ok, but at line
var textHeaders = await client.ReadAsync(urlFile);
website crashes.
I don't understand why. No error, it's just stopped.
So I ask: azure ocr can to be use only with console app?
EDIT
The code is ok for ConsoleApp and WebApp but not working for my asp.net WEBSITE.
Could be a problem with async?
We can use OCR with web app also,I have taken the .net core 3.1 webapp in Visual Studio and installed the dependency of Microsoft.Azure.CognitiveServices.Vision.ComputerVision by selecting the check mark of include prerelease as shown in the below image:
After creating computer vision resource in Azure Portal, copied the key and endpoint from there and used inside the c# code.
using System;
using System.Collections.Generic;
using Microsoft.Azure.CognitiveServices.Vision.ComputerVision;
using Microsoft.Azure.CognitiveServices.Vision.ComputerVision.Models;
using System.Threading.Tasks;
using System.IO;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Threading;
using System.Linq;
namespace ComputerVisionQuickstart
{
class Program
{
// Add your Computer Vision subscription key and endpoint
static string subscriptionKey = "c1****b********";
static string endpoint = ".abc.cognitiveservices.azure.com/";
private const string READ_TEXT_URL_IMAGE = "https://raw.githubusercontent.com/Azure-Samples/cognitive-services-sample-data-files/master/ComputerVision/Images/printed_text.jpg";
static void Main(string[] args)
{
Console.WriteLine("Azure Cognitive Services Computer Vision - .NET quickstart example");
Console.WriteLine();
ComputerVisionClient client = Authenticate(endpoint, subscriptionKey);
// Extract text (OCR) from a URL image using the Read API
ReadFileUrl(client, READ_TEXT_URL_IMAGE).Wait();
}
public static ComputerVisionClient Authenticate(string endpoint, string key)
{
ComputerVisionClient client =
new ComputerVisionClient(new ApiKeyServiceClientCredentials(key))
{ Endpoint = endpoint };
return client;
}
public static async Task ReadFileUrl(ComputerVisionClient client, string urlFile)
{
Console.WriteLine("----------------------------------------------------------");
Console.WriteLine("READ FILE FROM URL");
Console.WriteLine();
// Read text from URL
var textHeaders = await client.ReadAsync(urlFile);
// After the request, get the operation location (operation ID)
string operationLocation = textHeaders.OperationLocation;
Thread.Sleep(2000);
// Retrieve the URI where the extracted text will be stored from the Operation-Location header.
// We only need the ID and not the full URL
const int numberOfCharsInOperationId = 36;
string operationId = operationLocation.Substring(operationLocation.Length - numberOfCharsInOperationId);
// Extract the text
ReadOperationResult results;
Console.WriteLine($"Extracting text from URL file {Path.GetFileName(urlFile)}...");
Console.WriteLine();
do
{
results = await client.GetReadResultAsync(Guid.Parse(operationId));
}
while ((results.Status == OperationStatusCodes.Running ||
results.Status == OperationStatusCodes.NotStarted));
// Display the found text.
Console.WriteLine();
var textUrlFileResults = results.AnalyzeResult.ReadResults;
foreach (ReadResult page in textUrlFileResults)
{
foreach (Line line in page.Lines)
{
Console.WriteLine(line.Text);
}
}
Console.WriteLine();
}
}
}
The above code is taken from the Microsoft Document.
I can be able to read the text inside the image successfully as shown in the below screenshot:

Install a plugin to Liferay's editor

I have a Liferay DXP installation and I would like to install a plugin to the editor. The plugin is base64image.
I was following this official guide so I created a class generally like this:
#Component(immediate = true, service = DynamicInclude.class)
public class CKEditorBase64ImageDynamicInclude implements DynamicInclude {
private BundleContext bundleContext;
#Override
public void include(HttpServletRequest request, HttpServletResponse response, String key) throws IOException {
Bundle bundle = bundleContext.getBundle();
URL entryURL = bundle.getEntry("/META-INF/resources/html/editors/ckeditor/extension/base64_images.js");
StreamUtil.transfer(entryURL.openStream(), response.getOutputStream());
}
#Override
public void register(DynamicIncludeRegistry dynamicIncludeRegistry) {
dynamicIncludeRegistry.register("com.liferay.frontend.editors.web#ckeditor#onEditorCreate");
}
#Activate
protected void activate(BundleContext bundleContext) {
this.bundleContext = bundleContext;
}
}
It should include the base64_images.js file where it initializes the editor. But it never works, regardless what the content of the file is. What is wrong with that?
I would like to add that the plugin files (JavaScript code) are part of my Liferay theme. I wanted base64_images.js to call its API but it also might not be the correct way how to do it.

How to write client proxy for SPI and what the difference between client and server proxies?

I have developed own idGenerator based on Hazelcast IdGenerator class (with storing each last_used_id into db). Now I want to run hazelcast cluster as a single java application and my web-application as other app (web-application restart shouldn't move id values to next block). I move MyIdGeneratorProxy and MyIdGeneratorService to new application, run it, run web-application as a hazelcast-client and get
IllegalArgumentException: No factory registered for service: ecs:impl:idGeneratorService
It was okay when client and server were the same application.
It seems it's unable to process without some clientProxy. I have compared IdGeneratorProxy and ClientIdGeneratorProxy and it looks the same. What is the idea? How to write client proxy for services? I have found no documentation yet. Is direction of investigations correct? I thought it is possible to divide hazelcast inner services (like a id generator service) and my business-processes. Should I store custom ClientProxy (for custom spi) in my web-application?
This is a demo how to create a client proxy, the missing part CustomClientProxy function call, is quit complicated(more like a server proxy,here is called ReadRequest, the server is called Operation), you can find a how AtomicLong implement.For every client proxy method you have to make a request.
#Test
public void client() throws InterruptedException, IOException
{
ClientConfig cfg = new XmlClientConfigBuilder("hazelcast-client.xml").build();
ServiceConfig serviceConfig = new ServiceConfig();
serviceConfig.setName(ConnectorService.NAME)
.setClassName(ConnectorService.class.getCanonicalName())
.setEnabled(true);
ProxyFactoryConfig proxyFactoryConfig = new ProxyFactoryConfig();
proxyFactoryConfig.setService(ConnectorService.NAME);
proxyFactoryConfig.setClassName(CustomProxyFactory.class.getName());
cfg.addProxyFactoryConfig(proxyFactoryConfig);
HazelcastInstance hz = HazelcastClient.newHazelcastClient(cfg);
Thread.sleep(1000);
for (int i = 0; i < 10; i++)
{
Connector c = hz.getDistributedObject(ConnectorService.NAME, "Connector:" + ThreadLocalRandom.current()
.nextInt(10000));
System.out.println(c.snapshot());
}
}
private static class CustomProxyFactory implements ClientProxyFactory
{
#Override
public ClientProxy create(String id)
{
return new CustomClientProxy(ConnectorService.NAME, id);
}
}
private static class CustomClientProxy extends ClientProxy implements Connector
{
protected CustomClientProxy(String serviceName, String objectName)
{
super(serviceName, objectName);
}
#Override
public ConnectorState snapshot()
{
return null;
}
#Override
public void loadState(ConnectorState state)
{
}
#Override
public boolean reconnect(HostNode node)
{
return false;
}
#Override
public boolean connect()
{
return false;
}
}
EDIT
In hazelcast the IdGenerate is implemented as a wrapper for AtomicLong, you should implement you IdGenerate by you own, instead of extend IdGenerate.
So you have to implement these(more like a todo list XD):
API
interface MyIdGenerate
Server
MyIdGenerateService
MyIdGenerateProxy
MyIdGenerateXXXOperation
Client
ClientMyIdGenerateFactory
ClientMyIdGenerateProxy
MyIdGenerateXXXRequest
I also made a sequence(same as IdGenerate) here, this is backed by zookeeper or redis,also it's easy to add a db backend,too.I will integrate to hazelcast if I got time.

Using RazorEngine with TextWriter

I want to use RazorEngine to generate some html files. It's easy to generate strings first, then write them to files. But if the generated strings are too large, that will cause memory issues.
So I wonder is there a non-cached way to use RazorEngine, like using StreamWriter as its output rather than a string.
I google this for a while, but with no luck.
I think use a custom base template should be the right way, but the documents are so few(even out of date) on the offcial homepage of RazorEngine.
Any hint will be helpful!
OK. I figured it out.
Create a class that inherits TemplateBase<T>, and take a TextWrite parameter in the constructor.
public class TextWriterTemplate<T> : TemplateBase<T>
{
private readonly TextWriter _tw;
public TextWriterTemplate(TextWriter tw)
{
_tw = tw;
}
// override Write and WriteLiteral methods, write text using the TextWriter.
public override void Write(object value)
{
_tw.Write(value);
}
public override void WriteLiteral(string literal)
{
_tw.Write(literal);
}
}
Then use the template as this:
private static void Main(string[] args)
{
using (var sw = new StreamWriter(#"output.txt"))
{
var config = new FluentTemplateServiceConfiguration(c =>
c.WithBaseTemplateType(typeof(TextWriterTemplate<>))
.ActivateUsing(context => (ITemplate)Activator.CreateInstance(context.TemplateType, sw))
);
using (var service = new TemplateService(config))
{
service.Parse("Hello #Model.Name", new {Name = "Waku"}, null, null);
}
}
}
The content of output.txt should be Hello WAKU.

RemotingException was unhandled "Attempted to call a method declared on type 'System.IFormattable' on an object which exposes 'HES.MyProcess'."

i started to work with .net remoting, read myself through tutorials and explanations, saw now at least three examples on the web and they looked all similar to my code. i can't find the reason for the error I get. (RemotingException was unhandled "Attempted to call a method declared on type 'System.IFormattable' on an object which exposes 'HES.MyProcess'.")
I tried to fix this for six hours now, unsuccessfully looking up the internet, reading through lots of pages...
Maybe you guys can help me out ?
MarshalByRefObject deriving class looks like:
public class MyProcess : MarshalByRefObject, IMyProcess
{
//public System.Diagnostics.Process process {get; set;}
public MyProcess()
{
// TODO: Complete member initialization
// this.process = Process.GetCurrentProcess();
}
public string GetProcessId()
{ Console.WriteLine("I'm on..");
return "test";
// return this.process.Id;
}
}
My interface loooks like this:
interface IMyProcess
{
string GetProcessId();
}
My server looks like this:
namespace HES
{
public class HES_Starter
{
public static void Main(string[] args)
{
// using TCP protocol
TcpChannel channel = new TcpChannel(_port);
//second value is for security settings
ChannelServices.RegisterChannel(channel, false);
Console.WriteLine("HES Server here... on PID: " + Process.GetCurrentProcess().Id);
//Type, objectUri to access the object remotely, mode
RemotingConfiguration.RegisterWellKnownServiceType(
typeof(HES.MyProcess), "HESProcess",
WellKnownObjectMode.Singleton);
Console.ReadLine();
}
}
}
and finally my client like that:
namespace Service_Provider
{
public class Program
{
public static void Main(string[] args)
{
TcpChannel channel = new TcpChannel();
//second value is for security settings
ChannelServices.RegisterChannel(channel, false);
Console.WriteLine("HES Client here...");
IMyProcess remoteProcess = (IMyProcess)Activator.GetObject(
typeof(IMyProcess), "tcp://localhost:8050/HESProcess");
Console.WriteLine(remoteProcess);
Console.WriteLine(remoteProcess.GetProcessId());
Console.ReadLine();
}
}
}
does anybody have a clue what i'm doing wrong ?
I mean from the exception I can see that the client knows that the object is an remote object in the 'HES' namespace. And in debug I can see that the object
remoteProcess = {System.Runtime.Remoting.Proxies.__TransparentProxy}
is a proxy...
I don't know what i'm doing wrong here.

Resources