problems to handle some 5.0 language features -- enums and annotations -- in a custom doclet - enums

I am writing a brand new custom doclet using JDK 1.7. These are the problems I have found so far:
Doc methods isAnnotationType(), isAnnotationTypeElement(), isEnum() and isEnumConstant() do not work. They always return false.
PackageDoc method enums() does not work. It always returns an empty array. Enums are included in the result of methods allClasses() and ordinaryClasses().
ClassDoc method enumConstants() does not work. It always returns an empty array. Enum constants are included in the result of method fields().
PackageDoc method annotationTypes() does not work. It always returns an empty array. Annotations are included in the result of method interfaces(), so I could implement the following work-around:
AnnotationTypeDoc annotationDoc;
ClassDoc[] interfaces = packageDoc.interfaces();
for (ClassDoc classDoc : interfaces) {
if (classDoc instanceof AnnotationTypeDoc) {
annotationDoc = (AnnotationTypeDoc) classDoc;
} else {
continue;
}
process(annotationDoc);
}
Based on something that I found in the "What's New in Javadoc 5.0" page (http://docs.oracle.com/javase/7/docs/technotes/guides/javadoc/whatsnew-1.5.0.html) I am guessing that, even though I am writing it with JDK 1.7, my doclet is working in some kind of pre-5.0 compatibility mode. This is what I found in the "What's New in Javadoc 5.0" page:
Incompatibilities with Custom Doclets
Custom doclets written prior to 5.0 will have compatibility problems when run on source files that use new language features in 5.0.
New Language Features: The Doclet API and standard doclet were revised to handle the new 5.0 language features -- generics, enums, varargs and annotations.
To handle these features, custom doclets would also need to be revised.
The Javadoc tool tries -- to the extent possible -- to present so-called "legacy" doclets with a view of the program that
1) continues to work with pre-5.0 source code, and
2) matches their expectations for 5.0 source code.
So, for example, type parameters and type arguments are stripped from generic constructs, type variables and wildcard types are replaced by their erasures, and ClassDoc.fields() will return enum constants.

Solved! It really was working in pre-5.0 compatibility mode. All I had to do to was to add the following method to my custom doclet:
public static LanguageVersion languageVersion() {
return LanguageVersion.JAVA_1_5;
}

Related

How to check if an object conforms to the schema of an interface in typescript?

I have an interface which has certain properties defined.
For example:
interface Student {
name: string;
dob:string;
age:number;
city:string;
}
I read a JSON file which contains a record in this format and assign it to a variable.
let s1:Student = require('./student.json');
Now, I want to verify if s1 contains all the properties mentioned in interface Student. At runtime this is not validated. Is there any way I can do this?
There is an option of type guards, but that won't serve the purpose here. I do not know which fields would come from the JSON file. I also cannot add a discriminator(No data manipulation);
Without explicitly writing code to do so, this isn't possible in TypeScript. Why? Because once it's gone through the compiler, your code looks like this:
let s1 = require('./student.json');
Everything relating to types gets erased once compilation completes, leaving you with just the pure JavaScript. TypeScript will never emit code to verify that the type checks will actually hold true at runtime - this is explicitly outside of the language's design goals.
So, unfortunately, if you want this functionality you're going to have to write if (s1.name), if (s1.dob), etc.
(That said, it is worth noting that there are third-party projects which aim to add runtime type checking to TypeScript, but they're still experimental and it's doubtful they'll every become part of the actual TypeScript language.)

what does this closure looking code in groovy means?

I am experimenting with some gradle at a new project, and in its settings.gradle, file I see these few lines that I am unable to make sense of as to what groovy structure or a language feature it is and what it does and how it works:
plugins {
id "com.gradle.build-scan" version "1.12.1"
id "cz.malohlava" version "1.0.3"
}
buildScan {
server = "some.host.com"
publishAlways()
}
I was suspecting it was either a a closure or an interface of some sort, but could not make head or tail of it.
Any help in understanding following will be a great help:
what it does?
How plugins and buildScan works here from the language's perspective?
From the language perspective, the closures are executed in the context of another objects than the build script. This is called delegation in Groovy.
http://groovy-lang.org/closures.html#_delegation_strategy
plugin delegates to https://docs.gradle.org/current/dsl/org.gradle.plugin.use.PluginDependenciesSpec.html
buildScan delegates to Build Scan Plugin's extension object which configures the plugin.
There may be some trickery here that I don't understand, particularly as I can't find either plugins() or buildScan() in the API docs. Nonetheless, the following is a reasonable reading of what the syntax means.
plugins {} and buildScan {} are both methods that take a closure (see other answers for explanation of this) as an argument.
Each closure has a delegate object of a particular type that's different depending on the method using the closure, i.e. the delegate of plugins() will be of a different type to the delegate of buildScan()
Within the closure, unqualified methods and properties will be executed against the delegate object. So for the plugins {} block, id(...).version(...) will be called against its delegate. For buildScan {}, you're setting the property server on the delegate and calling its publishAlways() method.
Honestly, I don't know how useful the above information is for using and understanding Gradle, but I think it's what you're asking for. Hope it helps!

Drawbacks of javac -parameters flag

I want to try some frameworks features that required names of parameter in runtime, so I need to compile my app with -parameters and it will store the names of parameter in JVM byte code.
Which drawbacks except the size of jar/war exist of this parameter usage?
The addition of parameter names to the class file format is covered by JEP 118, which was delivered in Java 8. There was a little bit of discussion about why inclusion of parameter names was made optional in OpenJDK email threads here and here. Briefly, the stated reasons to make parameter names optional are concerns about class file size, compatibility surface, and exposure of sensitive information.
The issue of compatibility surface deserves some additional discussion. One of the threads linked above says that changing a parameter name is a binary compatible change. This is true, but only in the strict context of the JVM's notion of binary compatibility. That is, changing a parameter name of a method will never change whether or not that method can be linked by the JVM. But the statement doesn't hold for compatibility in general.
Historically, parameter names have been treated like local variable names. (They are, after all, local in scope.) You could change them at will and nothing outside the method will be affected. But if you enable reflective access to parameter names, suddenly you can't change a name without thinking about what other parts of the program might be using it. Worse, there's nothing that can tell you unless you have strict test cases for all uses of parameter names, or you have a really good static analyzer that can find these cases (I'm not aware of one).
The comments linked to a question about using Jackson (a JSON processing library) which has a feature that maps method parameter names to JSON property names. This may be quite convenient, but it also means that if you change a parameter name, JSON binding might break. Worse, if the program is generating JSON structures based on Java method parameter names, then changing a method parameter name might silently change a data format or wire protocol. Clearly, in such an environment, using this feature reliably means that you have to have very good tests, plus comments sprinkled around the code indicating what parameter names mustn't be changed.
The only thing is the size of the .class that will change, since the bytecode will now contain more information:
public class DeleteMe3 {
public static void main(String[] args) {
}
private static void go(String s) {
}
}
For example this will contain information about paramter names like so:
private static void go(java.lang.String);
descriptor: (Ljava/lang/String;)V
flags: ACC_PRIVATE, ACC_STATIC
Code:
stack=0, locals=1, args_size=1
0: return
LineNumberTable:
line 11: 0
MethodParameters:
Name Flags
s
This MethodParameters will simply not be present without -parameters.
There might be frameworks that don't play nice with this. Here is one Spring Data JPA Issue. I know about it because we hit it some time ago and had to upgrade (I have not been faced with any other from there on).

Can I Write a Spotlight Importer in Swift?

I need to write a Spotlight Importer for an application that I've written in Swift, and am referring to the official Apple guide for Writing a Spotlight Importer.
It seems straightforward enough, however creating a Spotlight Importer project creates a default setup for an Objective-C implementation. Now, working with Objective-C isn't a huge problem (I've used it plenty of times in the past) but everything I've written for my application is in Swift, so I'd really I'd like to write the importer in Swift too to avoid switching between languages, and also so I can share some of the code that I've already done for reading/writing files.
Firstly, is it possible to write a Spotlight Importer using Swift instead of Objective-C? And if it is, where should I start (e.g- if I take the Objective-C starting point, what would I do to switch over to Swift instead)?
It took me a bit of time to get this to work.
Instead of adding Swift code to the mdimporter, I import an embedded framework already setup for my app.
I removed all the example code except main.c and GetMetadataForFile.m.
In the latter I import my framework where all the functionality now resides as Swift code.
The built mdimporter is added to the app.
In the File Inspector set Location to Relative to Build Products.
The app then adds the mdimporter with a Copy Files Build Phase.
Destination: Wrapper
Subpath: Contents/Library/Spotlight
The following needs to be added to the Run Search Paths build setting, as we are linking to the app's embedded frameworks.
#loader_path/../../../../../Frameworks
If you get compiler error that the framework module can't be found when building the app, depending on how your workspace is set up, you might need to modify your app's Scheme.
Turn off Parallelize Build
Add the Build targets in this sequence:
Frameworks project(s)
mdimporter project
App project
The additional benefit of having all the logic in a framework, is that it can be prototyped and verified in a Playground. A million times easier than debugging an mdimporter plugin.
Yes, it is possible to write a Spotlight Importer entirely* in Swift!
*except for a few lines of code in main.m
I've just published one here: https://github.com/foxglove/MCAPSpotlightImporter
Here's a detailed blog post about the implementation process:
https://foxglove.dev/blog/implementing-a-macos-search-plugin-for-robotics-data
The difficult part of this is implementing a plugin that's compatible with the CFPlugIn architecture. (The MDImporter-specific logic is relatively minimal.) The CFPlugIn API is based on Microsoft's COM and Apple's docs are almost 20 years old.
The plugin is expected to be a block of memory conforming to a certain memory layout — specifically, the first value in the block must be a pointer to a virtual function table (vtable) for the requested interface (in the case of a MDImporter, this is either MDImporterInterfaceStruct or MDImporterURLInterfaceStruct) or the base IUnknown interface. This layout is documented here.
I wanted to organize the Swift code into a class, but you can't control the memory layout of a Swift class instance. So I created a "wrapper" block of memory which holds the vtable and an unsafe pointer to the class instance. The class has a static func allocate() which uses UnsafeMutablePointer to allocate the wrapper block, create and store the class instance in it, and also initialize the vtable.
The vtable implements the standard COM base interface (IUnknown) functions (QueryInterface, AddRef, and Release) by grabbing the class instance out of the wrapper and calling the queryInterface(), addRef(), and release() methods on the instance. It also implements the Spotlight-specific ImporterImportURLData function (or ImporterImportData). Unfortunately, in my testing, it seemed like Spotlight did not pass the correct pointer to the wrapper struct as the first argument to ImporterImportURLData, so it was impossible to call a method on the class instance, so the function that actually imports attributes for a file had to be a global function. For this reason I wasn't able to make the plug-in implementation a more generic class that could be used with any interface — it has to be tied to a specific global importer function.
I'd encourage you to view the full source on GitHub, but in the interest of not being a link-only answer, here's the core functionality:
final class ImporterPlugin {
typealias VTable = MDImporterURLInterfaceStruct
typealias Wrapper = (vtablePtr: UnsafeMutablePointer<VTable>, instance: UnsafeMutableRawPointer)
let wrapperPtr: UnsafeMutablePointer<Wrapper>
var refCount = 1
let factoryUUID: CFUUID
private init(wrapperPtr: UnsafeMutablePointer<Wrapper>, factoryUUID: CFUUID) {
self.wrapperPtr = wrapperPtr
self.factoryUUID = factoryUUID
CFPlugInAddInstanceForFactory(factoryUUID)
}
deinit {
let uuid = UUID(factoryUUID)
CFPlugInRemoveInstanceForFactory(factoryUUID)
}
static func fromWrapper(_ plugin: UnsafeMutableRawPointer?) -> Self? {
if let wrapper = plugin?.assumingMemoryBound(to: Wrapper.self) {
return Unmanaged<Self>.fromOpaque(wrapper.pointee.instance).takeUnretainedValue()
}
return nil
}
func queryInterface(uuid: UUID) -> UnsafeMutablePointer<Wrapper>? {
if uuid == kMDImporterURLInterfaceID || uuid == IUnknownUUID {
addRef()
return wrapperPtr
}
return nil
}
func addRef() {
precondition(refCount > 0)
refCount += 1
}
func release() {
precondition(refCount > 0)
refCount -= 1
if refCount == 0 {
Unmanaged<ImporterPlugin>.fromOpaque(wrapperPtr.pointee.instance).release()
wrapperPtr.pointee.vtablePtr.deinitialize(count: 1)
wrapperPtr.pointee.vtablePtr.deallocate()
wrapperPtr.deinitialize(count: 1)
wrapperPtr.deallocate()
}
}
static func allocate(factoryUUID: CFUUID) -> Self {
let wrapperPtr = UnsafeMutablePointer<Wrapper>.allocate(capacity: 1)
let vtablePtr = UnsafeMutablePointer<VTable>.allocate(capacity: 1)
let instance = Self(wrapperPtr: wrapperPtr, factoryUUID: factoryUUID)
let unmanaged = Unmanaged.passRetained(instance)
vtablePtr.initialize(to: VTable(
_reserved: nil,
QueryInterface: { wrapper, iid, outInterface in
if let instance = ImporterPlugin.fromWrapper(wrapper) {
if let interface = instance.queryInterface(uuid: UUID(iid)) {
outInterface?.pointee = UnsafeMutableRawPointer(interface)
return S_OK
}
}
outInterface?.pointee = nil
return HRESULT(bitPattern: 0x8000_0004) // E_NOINTERFACE <https://github.com/apple/swift/issues/61851>
},
AddRef: { wrapper in
if let instance = ImporterPlugin.fromWrapper(wrapper) {
instance.addRef()
}
return 0 // optional
},
Release: { wrapper in
if let instance = ImporterPlugin.fromWrapper(wrapper) {
instance.release()
}
return 0 // optional
},
ImporterImportURLData: { _, mutableAttributes, contentTypeUTI, url in
// Note: in practice, the first argument `wrapper` has the wrong value passed to it, so we can't use it here
guard let contentTypeUTI = contentTypeUTI as String?,
let url = url as URL?,
let mutableAttributes = mutableAttributes as NSMutableDictionary?
else {
return false
}
var attributes: [AnyHashable: Any] = mutableAttributes as NSDictionary as Dictionary
// Call custom global function to import attributes
let result = importAttributes(&attributes, forFileAt: url, contentTypeUTI: contentTypeUTI)
mutableAttributes.removeAllObjects()
mutableAttributes.addEntries(from: attributes)
return DarwinBoolean(result)
}
))
wrapperPtr.initialize(to: (vtablePtr: vtablePtr, instance: unmanaged.toOpaque()))
return instance
}
}
Finally, I created an #objc class that exposes this allocate function to Obj-C, where I can call it from main.m, and return the pointer to the wrapper block from the factory function. This was necessary because I didn't want to use the unstable #_cdecl attribute to expose a Swift function directly to the plug-in loader.
#objc public final class PluginFactory: NSObject {
#objc public static func createPlugin(ofType type: CFUUID, factoryUUID: CFUUID) -> UnsafeMutableRawPointer? {
if UUID(type) == kMDImporterTypeID {
return UnsafeMutableRawPointer(ImporterPlugin.allocate(factoryUUID: factoryUUID).wrapperPtr)
}
return nil
}
}
// main.m
void *MyImporterPluginFactory(CFAllocatorRef allocator, CFUUIDRef typeID) {
return [PluginFactory createPluginOfType:typeID factoryUUID:CFUUIDCreateFromString(NULL, CFSTR("your plugin factory uuid"))];
}
See my blog post for more details.
Since Apple introduced Swift as a language to be perfectly compatible with any existing Objective-C project I would suggest you just start with whatever makes things easier for you.
If you know Swift best then nothing keeps you from using that – for whatever project you might want. If you want to follow a tutorial that was written for Objective-C and not updated for Swift yet, I think you have two choices (I'd personally recommend going for the second option for now):
Write the same logic written in Objective-C within the tutorial now in Swift from scratch (nearly everything possible in Objective-C is easily possible with Swift, too). For that you need to understand the basics of Objective-C and the corresponding syntax and features in Swift though.
Start with Objective-C to follow the tutorial and keep things easier at the beginning (no need to really understand the tutorials details). Then use the great possibility of mix and matching Swift code alongside Objective-C code to customize the code for your needs or to extend it with your own pre-existing classes.
More specifically on the second option:
If you want to write new classes just use Swift – you can perfectly use everything written in Objective-C from within Swift and vice versa. If you feel you need to change classes already written in Objective-C you have these options: Extend the class written in Objective-C with a new Swift class, re-write that specific file in Swift or just edit the Objective-C file directly.
To learn more on how to mix and match Swift code alongside Objective-C I recommend reading Apples official documentation. It's part of the free iBook "Using Swift with Cocoa and Objective-C" written by Apple engineers for developers.
Unfortunately Apple actually does seem to provide their template for a Spotlight Importer from within XCode for Objective-C only at the moment. Don't know why this is though – I can't see anything stopping them from supporting Swift. We should probably report this with Apples Bug Reporter to stress the fact that people are actually asking for this.
Hope I didn't overlook anything here, otherwise my answer will be pointless. ^^
UPDATE (request)
Here are some steps on where to begin to implement the first approach:
First create a Spotlight Importer project with the latest XCode version
– Create a new "Cocoa Touch" class named exactly the same as your pre-created main Objective-C classes (e.g. "MySpotlightImporter")
Choose Swift and "Create Bridging Header" when asked during class creation
– Re-implement the code written in the ObjC-MySpotlightImporter class within the Swift class (you might want to create a Cocoa App with Core Data support in Swift and Objective-C to get some idea of their differences)
– I'm not sure if you can rewrite the GetMetaDataFile.m in Swift, too, I couldn't figure that out in my test, so you maybe need to keep it around (for now)
– In case you receive any errors along the way that point to some missing configuration just search for the related files/classes in the projects "Build settings" and apply your changes there
I hope this helps to get you started and is specific enough. I tried to do the necessary changes myself in order to provide an example project in Swift but unfortunately I couldn't get it working in a limited time. You may want to consider providing your code publicly though (e.g. on GitHub with a link posted here) in case you decide to port it yourself so others can profit from this, too.
Good luck!

C# 3.0 Autoproperties - whats the difference?

0 What's the difference between the following?
public class MyClass
{
public bool MyProperty;
}
public class MyClass
{
public bool MyProperty { get; set; }
}
Is it just semantics?
Fields and properties have many differences other than semantic.
Properties can be overridden to provide different implementations in descendants.
Properties can help alleviate versioning problems. I.e. Changing a field to a property in a library requires a recompile of anything depending on that library.
Properties can have different accessibility for the getter and setter.
"Just semantics" always seems like a contradiction in terms to me. Yes, it changes the meaning of the code. No, that's not something I'd use the word "just" about.
The first class has a public field. The second class has a public property, backed by a private field. They're not the same thing:
If you later change the implementation of the property, you maintain binary compatibility. If you change the field to a property, you lose both binary and source compatibility.
Fields aren't seen by data-binding; properties are
Field access can't be breakpointed in managed code (AFAIK)
Exposing a field exposes the implementation of your type - exposing a property just talks about the contract of your type.
See my article about the goodness of properties for slightly more detail on this.
In that case, yes it is mostly semantics. It makes a difference for reflection and so forth.
However, if you want to make a change so that when MyProperty is set you fire an event for example you can easily modify the latter to do that. The former you can't. You can also specify the latter in an interface.
As there is so little difference but several potential advantages to going down the property route, I figure that you should always go down the property route.
The first one is just a public field, the second one is a so-called automatic property. Automatic properties are changed to regular properties with a backing field by the C# compiler.
Public fields and properties are equal in C# syntax, but they are different in IL (read this on a German forum recently, can't give you the source, sorry).
Matthias
The biggest difference is that you can add access modifiers to properties, for example like this
public class MyClass
{
public bool MyProperty { get; protected set; }
}
For access to the CLR fields and properties are different too. So if you have a field and you want to change it to a property later (for example when you want to add code to the setter) the interface will change, you will need to recompile all code accessing that field. With an Autoproperty you don't have this problem.
I am assuming you are not writing code that will be called by 3rd party developers that can’t recompile their code when you change your code. (E.g. that you don’t work for Microsoft writing the .Net framework it’s self, or DevExpress writing a control toolkip). Remember that Microsoft’s .NET framework coding standard is for the people writing the framework and tries to avoid a lot of problems that are not even issues if you are not writing a framework for use of 3rd party developers.
The 2nd case the defined a propriety, the only true advantage of doing is that that data binding does not work with fields. There is however a big political advantage in using proprieties, you get a lot less invalid complaints from other developers that look at your code.
All the other advantages for proprieties (that are well explained in the other answers to your questions) are not of interest to you at present, as any programmer using your code can change the field to a propriety later if need be and just recompile your solution.
However you are not likely to get stacked for using proprieties, so you make as well always use public proprieties rather the fields.

Resources