I am trying to build a offline gwt app using HTML5 cache manifest and
local storage, but to do that, i need to build the manifest file
listing all the GWT generated files, right?
Can i do this during the compile process or is it better to do this in
a shell script?
This should be done using a Linker, so that your resources are automatically added to the manifest at compile time. I know there exists an HTML5 cache manifest linker, since the GWT team has mentioned it a few times, but I don't know where the source is.
The closest alternative (and probably a good starting point for writing an HTML5 linker) is the Gears offline linker. Gears' offline manifests are pretty similar to HTML5's, so it's probably a matter of changing a few lines to make it work.
There's also an informative video about using GWT linkers to have your app take advantage of HTML5 Web Workers.
I just had to do this other day at work. Like the previous answer says, you just need to add a linker. Here's an example of one that creates a manifest file for the Safari user agent based on a template file.
// Specify the LinkerOrder as Post... this does not replace the regular GWT linker and runs after it.
#LinkerOrder(LinkerOrder.Order.POST)
public class GwtAppCacheLinker extends AbstractLinker {
public String getDescription() {
return "to create an HTML5 application cache manifest JSP template.";
}
public ArtifactSet link(TreeLogger logger, LinkerContext context, ArtifactSet artifacts) throws UnableToCompleteException {
ArtifactSet newArtifacts = new ArtifactSet(artifacts);
// search through each of the compilation results to find the one for Safari. Then
// generate application cache for that file
for (CompilationResult compilationResult : artifacts.find(CompilationResult.class)) {
// Only emit the safari version
for (SelectionProperty property : context.getProperties()) {
if (property.getName().equals("user.agent")) {
String value = property.tryGetValue();
// we only care about the Safari user agent in this case
if (value != null && value.equals("safari")) {
newArtifacts.add(createCache(logger, context, compilationResult));
break;
}
}
}
}
return newArtifacts;
}
private SyntheticArtifact createCache(TreeLogger logger, LinkerContext context, CompilationResult result)
throws UnableToCompleteException {
try {
logger.log(TreeLogger.Type.INFO, "Using the Safari user agent for the manifest file.");
// load a template JSP file into a string. This contains all of the files that we want in our cache
// manifest and a placeholder for the GWT javascript file, which will replace with the actual file next
String manifest = IOUtils.toString(getClass().getResourceAsStream("cache.template.manifest"));
// replace the placeholder with the real file name
manifest = manifest.replace("$SAFARI_HTML_FILE_CHECKSUM$", result.getStrongName());
// return the Artifact named as the file we want to call it
return emitString(logger, manifest, "cache.manifest.");
} catch (IOException e) {
logger.log(TreeLogger.ERROR, "Couldn't read cache manifest template.", e);
throw new UnableToCompleteException();
}
}
}
Use the gwt2go library's GWT Application Manifest generator to do precisely that. That was easy. :)
Related
I have proper .dotm template.
When I create a new file based on a template by double clicking in explorer it creates the correct file (based on this template). Created file size after save is 16Kb (without any content).
But if I want to use .CreateFromTemplate method in my code I cannot open a newly created .docx file in MS Word.
New file size is 207Kb (just like .dotm file). MS Word display "run-time error 5398" and not open the file.
I'm using nuget package DocumentFormat.OpenXml 2.19.0, Word 365 version 16.0.14931.20648 - 32bit and code like this:
using (WordprocessingDocument doc = WordprocessingDocument.CreateFromTemplate(templatePath))
{
doc.SaveAs(newFileName);
}
Google is silent about this error, ChatGPT says that:
The "Run-time Error 5398" error means that the file you are trying to open is corrupted or not a valid docx file. Possible reasons for this error may be the following:
The file was not saved correctly after making changes. Verify that the Save() method was called after making changes to the file.
The file was saved with the wrong extension, e.g. as DOTM instead of DOCX
The file was saved in an invalid format.
There may have been some unhandled exceptions in your code.
When I manually change the extension of a new file from docx to dotm, there is no error when opening, but the file does not open.
What am I doing wrong with CreateFromTemplate method?
I tried to reproduce the behavior you described, using the following unit tests:
public sealed class CreateFromTemplateTests
{
private readonly ITestOutputHelper _output;
public CreateFromTemplateTests(ITestOutputHelper output)
{
_output = output;
}
[Theory]
[InlineData("c:\\temp\\MacroEnabledTemplate.dotm", "c:\\temp\\MacroEnabledDocument.docm")]
[InlineData("c:\\temp\\Template.dotx", "c:\\temp\\Document.docx")]
public void CanCreateDocmFromDotm(string templatePath, string documentPath)
{
// Let's not attach the template, which is done by default. If a template is attached, the validator complains as follows:
// The element has unexpected child element 'http://schemas.openxmlformats.org/wordprocessingml/2006/main:attachedTemplate'.
using (var wordDocument = WordprocessingDocument.CreateFromTemplate(templatePath, false))
{
// Validate the document as created with CreateFromTemplate.
ValidateOpenXmlPackage(wordDocument);
// Save that document to disk so we can open it with Word, for example.
wordDocument.SaveAs(documentPath).Dispose();
}
using (WordprocessingDocument wordDocument = WordprocessingDocument.Open(documentPath, true))
{
// Validate the document that was opened from disk, just to see what Word would open.
ValidateOpenXmlPackage(wordDocument);
}
}
private void ValidateOpenXmlPackage(OpenXmlPackage openXmlPackage)
{
OpenXmlValidator validator = new(FileFormatVersions.Office2019);
List<ValidationErrorInfo> validationErrors = validator.Validate(openXmlPackage).ToList();
foreach (ValidationErrorInfo validationError in validationErrors)
{
_output.WriteLine(validationError.Description);
}
if (validationErrors.Any())
{
// Note that Word will most often be able to open the document even if there are validation errors.
throw new Exception("The validator found validation errors.");
}
}
}
In both tests, the documents are created without an issue. Looking at the Open XML markup, both documents look fine. However, while I don't get any runtime error, Word also does not open the macro-enabled document.
I am not sure why that happens. It might be related to your security settings.
Depending on whether or not you really need to use CreateFromTemplate(), you could create a .docm (rather than a .dotm) and create new macro-enabled documents by copying that .docm.
I opened an issue in the Open XML SDK project on GitHub.
I am customizing ICN (IBM Content Navigator) 2.0.3 and my requirement is to restrict user to upload files over 10mb and only allowed files are .pdf or .docx.
I know I have to extend / customize the AddContentItemDialog but there is very less detail on exactly how to do it, or any video on it. I'd appreciate if someone could guide.
Thanks
I installed the development environment but I am not sure how to extend the AddContentItemDialog.
public void applicationInit(HttpServletRequest request,
PluginServiceCallbacks callbacks) throws Exception {
}
I want to also know how to roll out the changes to ICN.
This can be easily extended. I would suggest to read the ICN red book for the details on how to do it. But it is pretty standard code.
Regarding rollout the code to ICN, there are two ways:
- If you are using plugin: just replace the Jar file on the server location and restart WAS.
- If you are using EDS: you need to redeploy the web service and restart WAS.
Hope this helps.
thanks
Although there are many ways to do this, one way indeed is tot extend, or augment the AddContentItemDialog as you qouted. After looking at the (rather poor IBM documentation) i figured you could probably use the onAdd event/method
Dojo/Aspect#around allows you to do exactly that, example:
require(["dojo/aspect", "ecm/widget/dialog/AddContentItemDialog"], function(aspect, AddContentItemDialog) {
aspect.around(AddContentItemDialog.prototype, "onAdd", function advisor(original) {
return function around() {
var files = this.addContentItemGeneralPane.getFileInputFiles();
var containsInvalidFiles = dojo.some(files, function isInvalid(file) {
var fileName = file.name.toLowerCase();
var extensionOK = fileName.endsWith(".pdf") || fileName.endsWith(".docx");
var fileSizeOK = file.size <= 10 * 1024 * 1024;
return !(extensionOK && fileSizeOK);
});
if (containsInvalidFiles) {
alert("You can't add that :)");
}else{
original.apply(this, arguments);
}
}
});
});
Just make sure this code gets executed before the actual dialog is opened. The best way to achieve this, is by wrapping this code in a new plugin.
Now on creating/deploying plugins -> The easiest way is this wizard for Eclipse (see also a repackaged version for newer eclipse versions). Just create a new arbitrary plugin, and paste this javascript code in the generated .js file.
Additionally it might be good to note that you're only limiting "this specific dialog" to upload specific files. It would probably be a good idea to also create a requestFilter to limit all possible uses of the addContent api...
I have to display content from the owl file namely the class names.. onto my browser, I am using GWT,eclipse to do so, could some one tell me the following :-
1)how do I integrate the owl file with the eclipse project?
2)How do I run queries from my java project to extract class names from the owl file?
3)Where can I get the protege api to nclude into my project?!
You could just store your .owl file anywhere inside your project or on any other location on your harddrive. You just provide a path to it, when you load/store it (see code below).
Take a look at the OWLAPI, it allows you to load an existing ontology and retrieve all classes from it. Your code could look like this:
private static void loadAndPrintEntities() {
OWLOntologyManager manager = OWLManager.createOWLOntologyManager();
IRI documentIRI = IRI.create("file:///C:/folder/", "your_rontology.owl");
try {
OWLOntology ontology = manager.loadOntologyFromOntologyDocument(documentIRI);
//Prints all axioms, not just classes
ontology.axioms().forEach(a -> System.out.println(a));
} catch (OWLOntologyCreationException e) {
e.printStackTrace();
}
}
Rather than trying to integrate the Protegé API into your project, I suggest you write a plugin for Protegé. There are some great examples that should get you started. Import this project into Eclipse, modify the content, build your plugin and drop it into Protegé. That's it, you're ready to go!
I have an Eclipse project that contains several source files, with a bunch of different encodings: some files are UTF8, some others are ISO-8859-1, others more are windows-1252.
Moreover, there are files whose encoding is explicit (it can bee seen in each file Properties window) while that of others is Inherited from container.
I need to convert them to UTF8 - and I've already found I can use iconv for that - see my answer here for details -, but since they're more than one thousand, I can't convert them one by one: is there any programmatic way to get the encoding from the IDE or something similar?
I'm on Windows, I may do some shell scripting and / or write auxiliary software.
The charset setting of project file could be found in ${PROJECT_FOLDER}/.settings/org.eclipse.core.resources.prefs
Since there are so many files in your project. Create a simple Eclipse plugin could reduce the effort. Here are the steps:
Select Eclipse menu item New > Project... > Plug-in Project
Accept default values and goto last page, choose Hello, World template.
Open and edit plugin.xml, adding required plugin org.eclipse.core.resources in Dependencies page.
Edit SampleAction.java, refer the sample code below..
Create a Debug Configuration for execute Eclipse Application.
Start the eclipse and import your project.
Select menu item Sample Menu to invoke public void run(IAction action).
Sample code of Eclipse resource API:
//import org.eclipse.core.resources.*;
//import org.eclipse.core.runtime.*;
public void run(IAction action) {
final boolean keepHistory = true;
IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject("yourProjectName");
project.accept(new IResourceVisitor() {
public boolean visit(IResource resource) {
IFile file = (IFile)resource;
try {
String charset = file.getCharset(true);
if (!"UTF-8".equals(charset)) {
InputStream is = file.getContents();
//convert to UTF-8 and save it
String str = new String(IOUtils.toByteArray(is), charset);
file.setContents(new ByteArrayInputStream(str.getBytes("UTF-8")), true, keepHistory, null);
//remove charset setting
file.setCharset("UTF-8", null);
}
} catch (Throwable e) {
//log error... maybe process later via project.getFile(new Path(projectRelativePath))
Activator.getDefault().getLog().log(new Status(IStatus.INFO, Activator.PLUGIN_ID,
file.getProjectRelativePath().toString(), e));
}
return false;
}
}, IResource.DEPTH_INFINITE, IResource.FILE);
}
I want to use the default XML editor (org.eclipse.wst.xml.ui) of Eclipse in an RCP application. I need to read the DOM of the xml file currently open. The plugin doesn't offer any extension point, so I'm trying to access the internal classes. I am aware that the I should not access the internal classes, but I don't have another option.
My approach is to create a fragment and an extension point to be able to read data from the plugin. I'm trying not to recompile the plugin, that's why I thought that a fragment was necessary. I just want to load it and extract the data at runtime.
So, my question is: is there another way to access the classes of a plugin? if yes, how?
Any tutorial, doc page or useful link for any of the methods is welcome.
Since nobody answered my question and I found the answer after long searches, I will post the answer for others to use if they bump into this problem.
To access a plugin at runtime you must create and extension point and an extension attached to it into the plugin that you are trying to access.
Adding classes to a plugin using a fragment is not recommended if you want to access those classes from outside of the plugin.
So, the best solution for this is to get the plugin source from the CVS Repository and make the modifications directly into the source of the plugin. Add extension points, extensions and the code for functionality.
Tutorials:
Getting the plugin from the CVS Repository:
http://www.eclipse.org/webtools/community/tutorials/DevelopingWTP/DevelopingWTP.html
Creating extensions and extension points and accessing them:
http://www.vogella.de/articles/EclipseExtensionPoint/article.html
http://www.eclipsezone.com/eclipse/forums/t97608.rhtml
I ended up extending XMLMultiPageEditorPart like this:
public class MultiPageEditor extends XMLMultiPageEditorPart implements
IResourceChangeListener {
#Override
public void resourceChanged(IResourceChangeEvent event) {
// TODO Auto-generated method stub
setActivePage(3);
}
public Document getDOM() {
int activePageIndex = getActivePage();
setActivePage(1);
StructuredTextEditor fTextEditor = (StructuredTextEditor) getSelectedPage();
IDocument document = fTextEditor.getDocumentProvider().getDocument(
fTextEditor.getEditorInput());
IStructuredModel model = StructuredModelManager.getModelManager()
.getExistingModelForRead(document);
Document modelDocument = null;
try {
if (model instanceof IDOMModel) {
// cast the structured model to a DOM Model
modelDocument = (Document) (((IDOMModel) model).getDocument());
}
} finally {
if (model != null) {
model.releaseFromRead();
}
}
setActivePage(activePageIndex);
return modelDocument;
}
}
This is not a clean implementation, but it gets the job done.