Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added ability to use IAsyncEnumerable to perform operation on classes implementing Java.Lang.Iterable #146

Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@

import org.burningwave.core.assembler.ComponentContainer;
import org.burningwave.core.assembler.ComponentSupplier;
import org.burningwave.core.assembler.StaticComponentContainer;
import org.burningwave.core.classes.ClassCriteria;
import org.burningwave.core.classes.ClassHunter;
import org.burningwave.core.classes.SearchConfig;
Expand All @@ -29,6 +30,18 @@
import java.util.Collection;

public class JNetReflectorHelper {
public static boolean getLoggingState() {
return StaticComponentContainer.ManagedLoggerRepository.isEnabled();
}

public static void setLoggingState(boolean value) {
if (value) {
StaticComponentContainer.ManagedLoggerRepository.enableLogging();
} else {
StaticComponentContainer.ManagedLoggerRepository.disableLogging();
}
}

public static Collection<Class<?>> find() {
ComponentSupplier componentSupplier = ComponentContainer.getInstance();
PathHelper pathHelper = componentSupplier.getPathHelper();
Expand Down
1 change: 1 addition & 0 deletions src/net/Common/Common.props
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
<None Include="..\Common\JNet.snk" Link="JNet.snk" />
</ItemGroup>
<ItemGroup Condition="'$(TargetFramework)' == 'net462'">
<PackageReference Include="Microsoft.Bcl.AsyncInterfaces" Version="7.0.0"/>
<Reference Include="Microsoft.CSharp" />
</ItemGroup>
<!-- Fix start https://github.com/dotnet/sourcelink/issues/572 -->
Expand Down
4 changes: 3 additions & 1 deletion src/net/JNet/JNet.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
<PackageId>MASES.JNet</PackageId>
<PackageReadmeFile>usage.md</PackageReadmeFile>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<RunAnalyzersDuringLiveAnalysis>False</RunAnalyzersDuringLiveAnalysis>
<RunAnalyzersDuringBuild>False</RunAnalyzersDuringBuild>
</PropertyGroup>
<ItemGroup>
<None Include="mases.jnet.targets" Pack="true" PackagePath="build" />
Expand Down Expand Up @@ -133,7 +135,7 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="MASES.CLIParser" Version="3.1.2" />
<PackageReference Include="MASES.JCOBridge" Version="2.5.4">
<PackageReference Include="MASES.JCOBridge" Version="2.5.5">
<IncludeAssets>All</IncludeAssets>
<PrivateAssets>None</PrivateAssets>
</PackageReference>
Expand Down
2 changes: 1 addition & 1 deletion src/net/JNet/Java/Lang/Iterable.cs
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ public Iterable(params object[] args) : base(args) { }
/// .NET implementations of <see href="https://docs.oracle.com/javase/8/docs/api/java/lang/Iterable.html"/>
/// </summary>
/// <typeparam name="T"><see href="https://docs.oracle.com/javase/8/docs/api/java/lang/Iterable.html"/></typeparam>
public class Iterable<T> : JVMBridgeBaseEnumerable<Iterable<T>, T>
public class Iterable<T> : MASES.JNet.Specific.JNetAsyncEnumerable<Iterable<T>, T>
{
/// <summary>
/// <see href="https://www.jcobridge.com/api-clr/html/P_MASES_JCOBridge_C2JBridge_JVMBridgeBase_ClassName.htm"/>
Expand Down
2 changes: 1 addition & 1 deletion src/net/JNet/Java/Util/Collection.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ public partial class Collection<E>
/// .NET implementations of <see href="https://docs.oracle.com/javase/8/docs/api/java/util/Collection.html"/>
/// </summary>
/// <typeparam name="E"><see href="https://docs.oracle.com/javase/8/docs/api/java/util/Collection.html"/></typeparam>
public class Collection<E> : Iterable<E>
public class Collection<E> : Java.Lang.Iterable<E>
{
/// <summary>
/// <see href="https://www.jcobridge.com/api-clr/html/P_MASES_JCOBridge_C2JBridge_JVMBridgeBase_IsInterface.htm"/>
Expand Down
107 changes: 107 additions & 0 deletions src/net/JNet/Specific/AsyncEnumerable.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
/*
* Copyright 2023 MASES s.r.l.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Refer to LICENSE for more information.
*/

using MASES.JCOBridge.C2JBridge.JVMInterop;
using MASES.JCOBridge.C2JBridge;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Threading;

namespace MASES.JNet.Specific
{
/// <summary>
/// An extension of <see cref="JVMBridgeBaseEnumerator{TObject}"/> implementing <see cref="IAsyncEnumerator{TObject}"/> used to manage Java Iterator in async way
/// </summary>
/// <typeparam name="TObject">The returning type of the iterator</typeparam>
public class JNetAsyncEnumerator<TObject> : JVMBridgeBasePrefetchableEnumerator<TObject>, IAsyncEnumerator<TObject>
{
readonly ManualResetEvent _sync = new ManualResetEvent(false);
readonly IEnumerator<TObject> enumeratorBase = default;
readonly CancellationToken _cancellationToken = default;
/// <summary>
/// Initialize a new <see cref="JNetAsyncEnumerator{TObject}"/>
/// </summary>
/// <param name="refObj">Reference to <see cref="IJavaObject"/> implementing Java Iterator</param>
/// <param name="extension">Extension from <see cref="JVMBridgeBaseEnumerable{TClass}"/></param>
/// <param name="cancellationToken"><see cref="CancellationToken"/> to use in the iteration</param>
public JNetAsyncEnumerator(IJavaObject refObj, IEnumerableExtension extension, CancellationToken cancellationToken)
: base(refObj, extension)
{
_cancellationToken = cancellationToken;
enumeratorBase = this;
}
/// <inheritdoc cref="JVMBridgeBasePrefetchEnumerator.DoWorkCycle"/>
protected override bool DoWorkCycle()
{
_sync.WaitOne();
_sync.Reset();
return !_cancellationToken.IsCancellationRequested;
}

/// <inheritdoc cref="IAsyncEnumerator{T}.Current"/>
TObject IAsyncEnumerator<TObject>.Current => enumeratorBase.Current;

/// <inheritdoc cref="IAsyncDisposable.DisposeAsync"/>
ValueTask IAsyncDisposable.DisposeAsync()
{
_sync.Set();
enumeratorBase.Dispose();
_sync.Dispose();
GC.SuppressFinalize(this);
return new ValueTask();
}
/// <inheritdoc cref="IAsyncEnumerator{T}.MoveNextAsync"/>
public ValueTask<bool> MoveNextAsync()
{
_sync.Set();
if (_cancellationToken.IsCancellationRequested) return new ValueTask<bool>(false);
var retVal = enumeratorBase.MoveNext();
return new ValueTask<bool>(retVal);
}
}

/// <summary>
/// An extension of <see cref="JVMBridgeBaseEnumerable{TClass, TObject}"/> implementing <see cref="IAsyncEnumerable{TObject}"/> to manage Java Iterable in async way
/// </summary>
/// <typeparam name="TClass">The class implementing <see cref="IJVMBridgeBase"/></typeparam>
/// <typeparam name="TObject">The type of objects to enumerate implementing <see cref="IJVMBridgeBase"/></typeparam>
public abstract class JNetAsyncEnumerable<TClass, TObject> : JVMBridgeBaseEnumerable<TClass, TObject>, IAsyncEnumerable<TObject>
where TClass : JVMBridgeBase, new()
{
/// <summary>
/// Create an instance of <see cref="JNetAsyncEnumerable{TClass, TObject}"/>
/// </summary>
public JNetAsyncEnumerable()
{
}
/// <summary>
/// Create an instance of <see cref="JNetAsyncEnumerable{TClass, TObject}"/>
/// </summary>
/// <param name="args">The arguments to send to base class <see cref="JVMBridgeBaseEnumerable{TClass,TObject}"/></param>
public JNetAsyncEnumerable(params object[] args)
: base(args)
{
}
/// <inheritdoc cref="IAsyncEnumerable{TObject}.GetAsyncEnumerator(CancellationToken)"/>
public IAsyncEnumerator<TObject> GetAsyncEnumerator(CancellationToken cancellationToken = default)
{
return new JNetAsyncEnumerator<TObject>(IExecute("iterator") as IJavaObject, this, cancellationToken);
}
}
}
2 changes: 2 additions & 0 deletions src/net/JNetReflector/JNetReflector.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,7 @@
<Compile Include="..\JNet\Java\Lang\VirtualMachineError.cs" Link="Java\Lang\VirtualMachineError.cs" />
<Compile Include="..\JNet\Java\Util\Collection.cs" Link="Java\Util\Collection.cs" />
<Compile Include="..\JNet\JNetCoreBase.cs" Link="JNetCoreBase.cs" />
<Compile Include="..\JNet\Specific\AsyncEnumerable.cs" Link="Specific\AsyncEnumerable.cs" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Templates\AllPackageClassesStubClassMainClass.template" />
Expand Down Expand Up @@ -150,5 +151,6 @@
<Folder Include="Java\Lang\Annotation\" />
<Folder Include="Java\Lang\Reflect\" />
<Folder Include="Java\Util\" />
<Folder Include="Specific\" />
</ItemGroup>
</Project>
22 changes: 21 additions & 1 deletion src/net/JNetReflector/JNetReflectorHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,12 +27,32 @@

namespace Org.Mases.Jnet
{
/// <summary>
/// An helper class to manage the Java class JNetReflectorHelper
/// </summary>
public class JNetReflectorHelper : JVMBridgeBase<JNetReflectorHelper>
{
public override string ClassName => "org.mases.jnet.JNetReflectorHelper";

/// <summary>
/// Enable or disable logging
/// </summary>
public static bool EnableLogging
{
get { return SExecute<bool>("getLoggingState"); }
set { SExecute("setLoggingState", value); }
}
/// <summary>
/// Find all <see cref="Class"/>es in the classpath
/// </summary>
/// <returns><see cref="Collection{E}"/> of <see cref="Class"/></returns>
public static Collection<Class> Find() => SExecute<Collection<Class>>("find");

/// <summary>
/// Find all <see cref="Class"/>es with <paramref name="packageOrModuleName"/>
/// </summary>
/// <param name="packageOrModuleName">Pattern to search</param>
/// <param name="isModule"><see langword="true"/> for modules, otherwise <see langword="false"/></param>
/// <returns><see cref="Collection{E}"/> of <see cref="Class"/></returns>
public static Collection<Class> Find(string packageOrModuleName, bool isModule) => SExecute<Collection<Class>>("find", packageOrModuleName, isModule);
}
}
64 changes: 55 additions & 9 deletions tests/net/JNetTest/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@
using MASES.JNet.Extensions;
using System.Diagnostics;
using Java.Lang;
using MASES.JCOBridge.C2JBridge;
using System.Threading.Tasks;
using System.Collections.Generic;

namespace MASES.JNetTest
{
Expand Down Expand Up @@ -50,39 +53,82 @@ static void Main(string[] args)
}
catch (System.Exception ex) { System.Console.WriteLine(ex.Message); }

TestIterator();
TestAsyncIterator().Wait();

TestExtensions();
}

static async Task TestAsyncIterator()
{
const int execution = 100;
Stopwatch w = Stopwatch.StartNew();
ArrayList<string> alist = new Java.Util.ArrayList<string>();
for (int i = 0; i < execution; i++)
{
alist.Add(i.ToString());
}
w.Stop();

await foreach (var item in alist.WithPrefetch())
{
if (!int.TryParse(item, out int i))
{
System.Console.WriteLine($"Failed to parse: {item}");
}
}
}

static void TestIterator()
{
const int execution = 100;
Stopwatch w = Stopwatch.StartNew();
ArrayList<string> alist = new Java.Util.ArrayList<string>();
for (int i = 0; i < execution; i++)
{
alist.Add(i.ToString());
}
w.Stop();

foreach (var item in alist.WithPrefetch())
{
if (!int.TryParse(item, out int i))
{
System.Console.WriteLine($"Failed to parse: {item}");
}
}
}

static void TestExtensions()
{
System.Collections.Generic.Dictionary<string, string> dict = new();
dict.Add("a", "a");
dict.Add("b", "b");
dict.Add("c", "c");
System.Collections.Generic.Dictionary<string, bool> dict = new();
dict.Add("true", true);
dict.Add("false", false);
dict.Add("true2", true);
var map = dict.ToMap();
var newDict = map.ToDictiony();

const int execution = 10000;
Stopwatch w = Stopwatch.StartNew();
Java.Util.ArrayList<string> alist = new Java.Util.ArrayList<string>();
Java.Util.ArrayList<int> alist = new Java.Util.ArrayList<int>();
for (int i = 0; i < execution; i++)
{
alist.Add(i.ToString());
alist.Add(i);
}
w.Stop();
System.Console.WriteLine($"ArrayList Elapsed ticks: {w.ElapsedTicks}");
w.Restart();
System.Collections.Generic.List<string> nlist = new System.Collections.Generic.List<string>();
System.Collections.Generic.List<int> nlist = new System.Collections.Generic.List<int>();
for (int i = 0; i < execution; i++)
{
nlist.Add(i.ToString());
nlist.Add(i);
}
w.Stop();
System.Console.WriteLine($"System.Collections.Generic.List Elapsed ticks: {w.ElapsedTicks}");

//var collection = newDict.Values.ToJCollection();
//var intermediate = collection.ToList<Map.Entry<string, string>>();
var list = alist.ToList(); // Raise an exception because iterator returns java/util/HashMap$Node which is not convertible to string
var list = alist.ToList();
}
}
}