use of org.dom4j.DocumentException in project maven-archetype by apache.
the class DefaultOldArchetype method createArchetype.
public void createArchetype(ArchetypeGenerationRequest request, File archetypeFile) throws ArchetypeDescriptorException, ArchetypeTemplateProcessingException {
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("basedir", request.getOutputDirectory());
parameters.put(Constants.PACKAGE, request.getPackage());
parameters.put("packageName", request.getPackage());
parameters.put(Constants.GROUP_ID, request.getGroupId());
parameters.put(Constants.ARTIFACT_ID, request.getArtifactId());
parameters.put(Constants.VERSION, request.getVersion());
// ---------------------------------------------------------------------
if (getLogger().isInfoEnabled()) {
getLogger().info("----------------------------------------------------------------------------");
getLogger().info("Using following parameters for creating project from Old (1.x) Archetype: " + request.getArchetypeArtifactId() + ":" + request.getArchetypeVersion());
getLogger().info("----------------------------------------------------------------------------");
for (Map.Entry<String, String> entry : parameters.entrySet()) {
String parameterName = entry.getKey();
String parameterValue = entry.getValue();
getLogger().info("Parameter: " + parameterName + ", Value: " + parameterValue);
}
}
// ----------------------------------------------------------------------
// Load the descriptor
// ----------------------------------------------------------------------
ArchetypeDescriptorBuilder builder = new ArchetypeDescriptorBuilder();
ArchetypeDescriptor descriptor;
URLClassLoader archetypeJarLoader;
InputStream is = null;
try {
URL[] urls = new URL[1];
urls[0] = archetypeFile.toURL();
archetypeJarLoader = new URLClassLoader(urls);
is = getStream(ARCHETYPE_DESCRIPTOR, archetypeJarLoader);
if (is == null) {
is = getStream(ARCHETYPE_OLD_DESCRIPTOR, archetypeJarLoader);
}
if (is == null) {
throw new ArchetypeDescriptorException("The " + ARCHETYPE_DESCRIPTOR + " descriptor cannot be found.");
}
descriptor = builder.build(new XmlStreamReader(is));
} catch (IOException e) {
throw new ArchetypeDescriptorException("Error reading the " + ARCHETYPE_DESCRIPTOR + " descriptor.", e);
} catch (XmlPullParserException e) {
throw new ArchetypeDescriptorException("Error reading the " + ARCHETYPE_DESCRIPTOR + " descriptor.", e);
} finally {
IOUtil.close(is);
}
// ----------------------------------------------------------------------
//
// ----------------------------------------------------------------------
String artifactId = request.getArtifactId();
File parentPomFile = new File(request.getOutputDirectory(), ARCHETYPE_POM);
File outputDirectoryFile;
boolean creating;
File pomFile;
if (parentPomFile.exists() && descriptor.isAllowPartial() && artifactId == null) {
outputDirectoryFile = new File(request.getOutputDirectory());
creating = false;
pomFile = parentPomFile;
} else {
if (artifactId == null) {
throw new ArchetypeTemplateProcessingException("Artifact ID must be specified when creating a new project from an archetype.");
}
outputDirectoryFile = new File(request.getOutputDirectory(), artifactId);
creating = true;
if (outputDirectoryFile.exists()) {
if (descriptor.isAllowPartial()) {
creating = false;
} else {
throw new ArchetypeTemplateProcessingException("Directory " + outputDirectoryFile.getName() + " already exists - please run from a clean directory");
}
}
pomFile = new File(outputDirectoryFile, ARCHETYPE_POM);
}
if (creating) {
if (request.getGroupId() == null) {
throw new ArchetypeTemplateProcessingException("Group ID must be specified when creating a new project from an archetype.");
}
if (request.getVersion() == null) {
throw new ArchetypeTemplateProcessingException("Version must be specified when creating a new project from an archetype.");
}
}
String outputDirectory = outputDirectoryFile.getAbsolutePath();
String packageName = request.getPackage();
// ----------------------------------------------------------------------
// Set up the Velocity context
// ----------------------------------------------------------------------
Context context = new VelocityContext();
context.put(Constants.PACKAGE, packageName);
for (Map.Entry<String, String> entry : parameters.entrySet()) {
context.put(entry.getKey(), entry.getValue());
}
// ----------------------------------------------------------------------
// Process the templates
// ----------------------------------------------------------------------
ClassLoader old = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(archetypeJarLoader);
Model parentModel = null;
if (creating) {
if (parentPomFile.exists()) {
Reader fileReader = null;
try {
fileReader = ReaderFactory.newXmlReader(parentPomFile);
MavenXpp3Reader reader = new MavenXpp3Reader();
parentModel = reader.read(fileReader);
if (!"pom".equals(parentModel.getPackaging())) {
throw new ArchetypeTemplateProcessingException("Unable to add module to the current project as it is not of packaging type 'pom'");
}
} catch (IOException e) {
throw new ArchetypeTemplateProcessingException("Unable to read parent POM", e);
} catch (XmlPullParserException e) {
throw new ArchetypeTemplateProcessingException("Unable to read parent POM", e);
} finally {
IOUtil.close(fileReader);
}
parentModel.getModules().add(artifactId);
}
}
try {
processTemplates(pomFile, outputDirectory, context, descriptor, packageName, parentModel);
} finally {
Thread.currentThread().setContextClassLoader(old);
}
if (parentModel != null) {
/*
// TODO: would be nice to just write out with the xpp3 writer again, except that it loses a bunch of info and
// reformats, so the module is just baked in as a string instead.
FileWriter fileWriter = null;
try
{
fileWriter = new FileWriter( parentPomFile );
MavenXpp3Writer writer = new MavenXpp3Writer();
writer.write( fileWriter, parentModel );
}
catch ( IOException e )
{
throw new ArchetypeTemplateProcessingException( "Unable to rewrite parent POM", e );
}
finally
{
IOUtil.close( fileWriter );
}
*/
Reader fileReader = null;
boolean added;
StringWriter w = new StringWriter();
try {
fileReader = ReaderFactory.newXmlReader(parentPomFile);
added = addModuleToParentPom(artifactId, fileReader, w);
} catch (IOException e) {
throw new ArchetypeTemplateProcessingException("Unable to rewrite parent POM", e);
} catch (DocumentException e) {
throw new ArchetypeTemplateProcessingException("Unable to rewrite parent POM", e);
} finally {
IOUtil.close(fileReader);
}
if (added) {
Writer out = null;
try {
out = WriterFactory.newXmlWriter(parentPomFile);
IOUtil.copy(w.toString(), out);
} catch (IOException e) {
throw new ArchetypeTemplateProcessingException("Unable to rewrite parent POM", e);
} finally {
IOUtil.close(out);
}
}
}
// ----------------------------------------------------------------------
if (getLogger().isInfoEnabled()) {
getLogger().info("project created from Old (1.x) Archetype in dir: " + outputDirectory);
}
}
use of org.dom4j.DocumentException in project maven-archetype by apache.
the class DefaultFilesetArchetypeGenerator method generateArchetype.
public void generateArchetype(ArchetypeGenerationRequest request, File archetypeFile) throws UnknownArchetype, ArchetypeNotConfigured, ProjectDirectoryExists, PomFileExists, OutputFileExists, ArchetypeGenerationFailure {
ClassLoader old = Thread.currentThread().getContextClassLoader();
try {
ArchetypeDescriptor archetypeDescriptor = archetypeArtifactManager.getFileSetArchetypeDescriptor(archetypeFile);
if (!isArchetypeConfigured(archetypeDescriptor, request)) {
if (request.isInteractiveMode()) {
throw new ArchetypeNotConfigured("No archetype was chosen.", null);
}
StringBuffer exceptionMessage = new StringBuffer("Archetype " + request.getArchetypeGroupId() + ":" + request.getArchetypeArtifactId() + ":" + request.getArchetypeVersion() + " is not configured");
List<String> missingProperties = new ArrayList<String>(0);
for (RequiredProperty requiredProperty : archetypeDescriptor.getRequiredProperties()) {
if (StringUtils.isEmpty(request.getProperties().getProperty(requiredProperty.getKey()))) {
exceptionMessage.append("\n\tProperty " + requiredProperty.getKey() + " is missing.");
missingProperties.add(requiredProperty.getKey());
}
}
throw new ArchetypeNotConfigured(exceptionMessage.toString(), missingProperties);
}
Context context = prepareVelocityContext(request);
String packageName = request.getPackage();
String artifactId = request.getArtifactId();
File outputDirectoryFile = new File(request.getOutputDirectory(), artifactId);
File basedirPom = new File(request.getOutputDirectory(), Constants.ARCHETYPE_POM);
File pom = new File(outputDirectoryFile, Constants.ARCHETYPE_POM);
List<String> archetypeResources = archetypeArtifactManager.getFilesetArchetypeResources(archetypeFile);
ZipFile archetypeZipFile = archetypeArtifactManager.getArchetypeZipFile(archetypeFile);
ClassLoader archetypeJarLoader = archetypeArtifactManager.getArchetypeJarLoader(archetypeFile);
Thread.currentThread().setContextClassLoader(archetypeJarLoader);
if (archetypeDescriptor.isPartial()) {
getLogger().debug("Processing partial archetype " + archetypeDescriptor.getName());
if (outputDirectoryFile.exists()) {
if (!pom.exists()) {
throw new PomFileExists("This is a partial archetype and the pom.xml file doesn't exist.");
}
processPomWithMerge(context, pom, "");
processArchetypeTemplatesWithWarning(archetypeDescriptor, archetypeResources, archetypeZipFile, "", context, packageName, outputDirectoryFile);
} else {
if (basedirPom.exists()) {
processPomWithMerge(context, basedirPom, "");
processArchetypeTemplatesWithWarning(archetypeDescriptor, archetypeResources, archetypeZipFile, "", context, packageName, new File(request.getOutputDirectory()));
} else {
processPom(context, pom, "");
processArchetypeTemplates(archetypeDescriptor, archetypeResources, archetypeZipFile, "", context, packageName, outputDirectoryFile);
}
}
if (archetypeDescriptor.getModules().size() > 0) {
getLogger().info("Modules ignored in partial mode");
}
} else {
getLogger().debug("Processing complete archetype " + archetypeDescriptor.getName());
if (outputDirectoryFile.exists() && pom.exists()) {
throw new ProjectDirectoryExists("A Maven 2 project already exists in the directory " + outputDirectoryFile.getPath());
}
if (outputDirectoryFile.exists()) {
getLogger().warn("The directory " + outputDirectoryFile.getPath() + " already exists.");
}
context.put("rootArtifactId", artifactId);
processFilesetModule(artifactId, artifactId, archetypeResources, pom, archetypeZipFile, "", basedirPom, outputDirectoryFile, packageName, archetypeDescriptor, context);
}
String postGenerationScript = archetypeArtifactManager.getPostGenerationScript(archetypeFile);
if (postGenerationScript != null) {
getLogger().info("Executing " + Constants.ARCHETYPE_POST_GENERATION_SCRIPT + " post-generation script");
Binding binding = new Binding();
final Properties archetypeGeneratorProperties = new Properties();
archetypeGeneratorProperties.putAll(System.getProperties());
if (request.getProperties() != null) {
archetypeGeneratorProperties.putAll(request.getProperties());
}
for (Map.Entry<Object, Object> entry : archetypeGeneratorProperties.entrySet()) {
binding.setVariable(entry.getKey().toString(), entry.getValue());
}
binding.setVariable("request", request);
GroovyShell shell = new GroovyShell(binding);
shell.evaluate(postGenerationScript);
}
// ----------------------------------------------------------------------
if (getLogger().isInfoEnabled()) {
getLogger().info("Project created from Archetype in dir: " + outputDirectoryFile.getAbsolutePath());
}
} catch (FileNotFoundException ex) {
throw new ArchetypeGenerationFailure(ex);
} catch (IOException ex) {
throw new ArchetypeGenerationFailure(ex);
} catch (XmlPullParserException ex) {
throw new ArchetypeGenerationFailure(ex);
} catch (DocumentException ex) {
throw new ArchetypeGenerationFailure(ex);
} catch (ArchetypeGenerationFailure ex) {
throw new ArchetypeGenerationFailure(ex);
} catch (InvalidPackaging ex) {
throw new ArchetypeGenerationFailure(ex);
} finally {
Thread.currentThread().setContextClassLoader(old);
}
}
use of org.dom4j.DocumentException in project azure-tools-for-java by Microsoft.
the class AddDependencyAction method applyVersionChanges.
private static boolean applyVersionChanges(SpringCloudDependencyManager dependencyManager, File pomFile, String springBootVer, Map<String, DependencyArtifact> managerDependencyVersionsMaps, List<DependencyArtifact> versionChanges) throws IOException, DocumentException {
versionChanges.stream().filter(change -> managerDependencyVersionsMaps.containsKey(change.getKey())).forEach(change -> {
String managementVersion = managerDependencyVersionsMaps.get(change.getKey()).getCurrentVersion();
if (StringUtils.equals(change.getCompatibleVersion(), managementVersion) || SpringCloudDependencyManager.isCompatibleVersion(managementVersion, springBootVer)) {
change.setCompatibleVersion("");
change.setManagementVersion(managementVersion);
}
});
return dependencyManager.update(pomFile, versionChanges);
}
use of org.dom4j.DocumentException in project mustangproject by ZUGFeRD.
the class ZUGFeRDValidator method validate.
/**
* performs a validation on the file filename
*
* @param filename the complete absolute filename of a PDF or XML
* @return a xml string with the validation result
*/
public String validate(String filename) {
boolean xmlValidity;
context.clear();
StringBuffer finalStringResult = new StringBuffer();
SimpleDateFormat isoDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date();
startTime = Calendar.getInstance().getTimeInMillis();
try {
Path path = Paths.get(filename);
// set filename without path
context.setFilename(path.getFileName().toString());
} catch (NullPointerException ex) {
// ignore
}
finalStringResult.append("<validation filename='" + context.getFilename() + "' datetime='" + isoDF.format(date) + "'>");
boolean isPDF = false;
try {
if (filename == null) {
optionsRecognized = false;
context.addResultItem(new ValidationResultItem(ESeverity.fatal, "Filename not specified").setSection(10).setPart(EPart.pdf));
}
PDFValidator pdfv = new PDFValidator(context);
File file = new File(filename);
if (!file.exists()) {
context.addResultItem(new ValidationResultItem(ESeverity.fatal, "File not found").setSection(1).setPart(EPart.pdf));
} else if (file.length() < 32) {
// with less then 32 bytes it can not even be a proper XML file
context.addResultItem(new ValidationResultItem(ESeverity.fatal, "File too small").setSection(5).setPart(EPart.pdf));
} else {
BigFileSearcher searcher = new BigFileSearcher();
XMLValidator xv = new XMLValidator(context);
if (disableNotices) {
xv.disableNotices();
}
byte[] pdfSignature = { '%', 'P', 'D', 'F' };
isPDF = searcher.indexOf(file, pdfSignature) == 0;
if (isPDF) {
pdfv.setFilename(filename);
optionsRecognized = true;
try {
if (!file.exists()) {
context.addResultItem(new ValidationResultItem(ESeverity.exception, "File " + filename + " not found").setSection(1));
}
} catch (IrrecoverableValidationError irx) {
// @todo log
}
finalStringResult.append("<pdf>");
optionsRecognized = true;
try {
pdfv.validate();
sha1Checksum = calcSHA1(file);
// Validate PDF
finalStringResult.append(pdfv.getXMLResult());
pdfValidity = context.isValid();
Signature = context.getSignature();
// clear sets valid to true again
context.clear();
if (pdfv.getRawXML() != null) {
xv.setStringContent(pdfv.getRawXML());
displayXMLValidationOutput = true;
} else {
context.addResultItem(new ValidationResultItem(ESeverity.exception, "XML could not be extracted").setSection(17));
}
} catch (IrrecoverableValidationError irx) {
// @todo log
}
finalStringResult.append("</pdf>\n");
context.clearCustomXML();
} else {
boolean isXML = false;
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
byte[] content = Files.readAllBytes(file.toPath());
content = XMLTools.removeBOM(content);
String s = new String(content, StandardCharsets.UTF_8);
InputSource is = new InputSource(new StringReader(s));
Document doc = db.parse(is);
Element root = doc.getDocumentElement();
// no exception so far
isXML = true;
} catch (Exception ex) {
// probably no xml file, sth like SAXParseException content not allowed in prolog
// ignore isXML is already false
// in the tests, this may error-out anyway
// ex.printStackTrace();
}
if (isXML) {
pdfValidity = true;
optionsRecognized = true;
xv.setFilename(filename);
if (file.exists()) {
sha1Checksum = calcSHA1(file);
}
displayXMLValidationOutput = true;
} else {
optionsRecognized = false;
context.addResultItem(new ValidationResultItem(ESeverity.exception, "File does not look like PDF nor XML (contains neither %PDF nor <?xml)").setSection(8));
}
}
if ((optionsRecognized) && (displayXMLValidationOutput)) {
finalStringResult.append("<xml>");
try {
xv.validate();
} catch (IrrecoverableValidationError irx) {
// @todo log
}
finalStringResult.append(xv.getXMLResult());
finalStringResult.append("</xml>");
context.clearCustomXML();
}
if ((isPDF) && (!pdfValidity)) {
context.setInvalid();
}
}
} catch (IrrecoverableValidationError irx) {
// @todo log
} finally {
finalStringResult.append(context.getXMLResult());
finalStringResult.append("</validation>");
}
OutputFormat format = OutputFormat.createPrettyPrint();
StringWriter sw = new StringWriter();
org.dom4j.Document document = null;
try {
document = DocumentHelper.parseText(new String(finalStringResult));
} catch (DocumentException e1) {
LOGGER.error(e1.getMessage());
}
XMLWriter writer = new XMLWriter(sw, format);
try {
writer.write(document);
} catch (Exception e) {
LOGGER.error(e.getMessage());
}
xmlValidity = context.isValid();
long duration = Calendar.getInstance().getTimeInMillis() - startTime;
String toBeAppended = "";
if (logAppend != null) {
toBeAppended = logAppend;
}
String pdfResult = "invalid";
if (!isPDF) {
pdfResult = "absent";
} else if (pdfValidity) {
pdfResult = "valid";
}
LOGGER.info("Parsed PDF:" + pdfResult + " XML:" + (xmlValidity ? "valid" : "invalid") + " Signature:" + Signature + " Checksum:" + sha1Checksum + " Profile:" + context.getProfile() + " Version:" + context.getGeneration() + " Took:" + duration + "ms Errors:[" + context.getCSVResult() + "] " + toBeAppended);
wasCompletelyValid = ((pdfValidity) && (xmlValidity));
return sw.toString();
}
use of org.dom4j.DocumentException in project mustangproject by ZUGFeRD.
the class ZUGFeRD1PullProvider method getXML.
@Override
public byte[] getXML() {
byte[] res = zugferdData;
final StringWriter sw = new StringWriter();
Document document = null;
try {
document = DocumentHelper.parseText(new String(zugferdData));
} catch (final DocumentException e1) {
Logger.getLogger(ZUGFeRD1PullProvider.class.getName()).log(Level.SEVERE, null, e1);
}
try {
final OutputFormat format = OutputFormat.createPrettyPrint();
format.setTrimText(false);
final XMLWriter writer = new XMLWriter(sw, format);
writer.write(document);
res = sw.toString().getBytes("UTF-8");
} catch (final IOException e) {
Logger.getLogger(ZUGFeRD1PullProvider.class.getName()).log(Level.SEVERE, null, e);
}
return res;
}
Aggregations