List of usage examples for org.apache.commons.lang StringUtils stripStart
public static String stripStart(String str, String stripChars)
Strips any of a set of characters from the start of a String.
From source file:org.codehaus.mojo.mrm.impl.maven.MemoryArtifactStore.java
/** * {@inheritDoc}/*from w ww . j a v a 2 s . com*/ */ public synchronized long getMetadataLastModified(String path) throws IOException, MetadataNotFoundException { boolean haveResult = false; long result = 0; path = StringUtils.stripEnd(StringUtils.stripStart(path, "/"), "/"); String groupId = path.replace('/', '.'); Map artifactMap = (Map) contents.get(groupId); if (artifactMap != null) { for (Iterator i = artifactMap.values().iterator(); i.hasNext();) { Map versionMap = (Map) i.next(); for (Iterator j = versionMap.values().iterator(); j.hasNext();) { Map filesMap = (Map) j.next(); for (Iterator k = filesMap.values().iterator(); k.hasNext();) { Content content = (Content) k.next(); haveResult = true; result = Math.max(result, content.getLastModified()); } } } } int index = path.lastIndexOf('/'); groupId = index == -1 ? groupId : groupId.substring(0, index).replace('/', '.'); String artifactId = (index == -1 ? null : path.substring(index + 1)); if (artifactId != null) { artifactMap = (Map) contents.get(groupId); Map versionMap = (Map) (artifactMap == null ? null : artifactMap.get(artifactId)); if (versionMap != null) { for (Iterator j = versionMap.values().iterator(); j.hasNext();) { Map filesMap = (Map) j.next(); for (Iterator k = filesMap.values().iterator(); k.hasNext();) { Content content = (Content) k.next(); haveResult = true; result = Math.max(result, content.getLastModified()); } } } } int index2 = index == -1 ? -1 : path.lastIndexOf('/', index - 1); groupId = index2 == -1 ? groupId : groupId.substring(0, index2).replace('/', '.'); artifactId = index2 == -1 ? artifactId : path.substring(index2 + 1, index); String version = index2 == -1 ? null : path.substring(index + 1); if (version != null && version.endsWith("-SNAPSHOT")) { artifactMap = (Map) contents.get(groupId); Map versionMap = (Map) (artifactMap == null ? null : artifactMap.get(artifactId)); Map filesMap = (Map) (versionMap == null ? null : versionMap.get(version)); if (filesMap != null) { for (Iterator k = filesMap.values().iterator(); k.hasNext();) { Content content = (Content) k.next(); haveResult = true; result = Math.max(result, content.getLastModified()); } } } if (haveResult) { return result; } throw new MetadataNotFoundException(path); }
From source file:org.codehaus.mojo.mrm.impl.maven.MockArtifactStore.java
/** * {@inheritDoc}/*from w w w. jav a 2 s . c o m*/ */ public synchronized Metadata getMetadata(String path) throws IOException, MetadataNotFoundException { Metadata metadata = new Metadata(); boolean foundMetadata = false; path = StringUtils.stripEnd(StringUtils.stripStart(path, "/"), "/"); String groupId = path.replace('/', '.'); Set<String> pluginArtifactIds = getArtifactIds(groupId); if (pluginArtifactIds != null) { List<Plugin> plugins = new ArrayList<Plugin>(); for (String artifactId : pluginArtifactIds) { Set<String> pluginVersions = getVersions(groupId, artifactId); if (pluginVersions == null || pluginVersions.isEmpty()) { continue; } String[] versions = pluginVersions.toArray(new String[pluginVersions.size()]); Arrays.sort(versions, new VersionComparator()); MavenXpp3Reader reader = new MavenXpp3Reader(); for (int j = versions.length - 1; j >= 0; j--) { InputStream inputStream = null; try { inputStream = get(new Artifact(groupId, artifactId, versions[j], "pom")); Model model = reader.read(new XmlStreamReader(inputStream)); if (model == null || !"maven-plugin".equals(model.getPackaging())) { continue; } Plugin plugin = new Plugin(); plugin.setArtifactId(artifactId); plugin.setName(model.getName()); // TODO proper goal-prefix determination // ugh! this is incredibly hacky and does not handle some fool that sets the goal prefix in // a parent pom... ok unlikely, but stupid is as stupid does boolean havePrefix = false; final Build build = model.getBuild(); if (build != null && build.getPlugins() != null) { havePrefix = setPluginGoalPrefixFromConfiguration(plugin, build.getPlugins()); } if (!havePrefix && build != null && build.getPluginManagement() != null && build.getPluginManagement().getPlugins() != null) { havePrefix = setPluginGoalPrefixFromConfiguration(plugin, build.getPluginManagement().getPlugins()); } if (!havePrefix && artifactId.startsWith("maven-") && artifactId.endsWith("-plugin")) { plugin.setPrefix(StringUtils.removeStart(StringUtils.removeEnd(artifactId, "-plugin"), "maven-")); havePrefix = true; } if (!havePrefix && artifactId.endsWith("-maven-plugin")) { plugin.setPrefix(StringUtils.removeEnd(artifactId, "-maven-plugin")); havePrefix = true; } if (!havePrefix) { plugin.setPrefix(artifactId); } plugins.add(plugin); foundMetadata = true; break; } catch (ArtifactNotFoundException e) { // ignore } catch (XmlPullParserException e) { // ignore } finally { IOUtils.closeQuietly(inputStream); } } } if (!plugins.isEmpty()) { metadata.setPlugins(plugins); } } int index = path.lastIndexOf('/'); groupId = (index == -1 ? groupId : groupId.substring(0, index)).replace('/', '.'); String artifactId = (index == -1 ? null : path.substring(index + 1)); if (artifactId != null) { Set<String> artifactVersions = getVersions(groupId, artifactId); if (artifactVersions != null && !artifactVersions.isEmpty()) { metadata.setGroupId(groupId); metadata.setArtifactId(artifactId); Versioning versioning = new Versioning(); List<String> versions = new ArrayList<String>(artifactVersions); Collections.sort(versions, new VersionComparator()); // sort the Maven way long lastUpdated = 0; for (String version : versions) { try { long lastModified = getLastModified(new Artifact(groupId, artifactId, version, "pom")); versioning.addVersion(version); if (lastModified >= lastUpdated) { lastUpdated = lastModified; versioning.setLastUpdatedTimestamp(new Date(lastModified)); versioning.setLatest(version); if (!version.endsWith("-SNAPSHOT")) { versioning.setRelease(version); } } } catch (ArtifactNotFoundException e) { // ignore } } metadata.setVersioning(versioning); foundMetadata = true; } } int index2 = index == -1 ? -1 : path.lastIndexOf('/', index - 1); groupId = index2 == -1 ? groupId : groupId.substring(0, index2).replace('/', '.'); artifactId = index2 == -1 ? artifactId : path.substring(index2 + 1, index); String version = index2 == -1 ? null : path.substring(index + 1); if (version != null && version.endsWith("-SNAPSHOT")) { Map<String, Map<String, Map<Artifact, Content>>> artifactMap = contents.get(groupId); Map<String, Map<Artifact, Content>> versionMap = (artifactMap == null ? null : artifactMap.get(artifactId)); Map<Artifact, Content> filesMap = (versionMap == null ? null : versionMap.get(version)); if (filesMap != null) { List<SnapshotVersion> snapshotVersions = new ArrayList<SnapshotVersion>(); int maxBuildNumber = 0; long lastUpdated = 0; String timestamp = null; boolean found = false; for (final Map.Entry<Artifact, Content> entry : filesMap.entrySet()) { final Artifact artifact = entry.getKey(); final Content content = entry.getValue(); SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMddHHmmss"); fmt.setTimeZone(TimeZone.getTimeZone("GMT")); String lastUpdatedTime = fmt.format(new Date(content.getLastModified())); try { Maven3.addSnapshotVersion(snapshotVersions, artifact, lastUpdatedTime); } catch (LinkageError e) { // Maven 2 } if ("pom".equals(artifact.getType())) { if (artifact.getBuildNumber() != null && maxBuildNumber < artifact.getBuildNumber().intValue()) { maxBuildNumber = artifact.getBuildNumber().intValue(); timestamp = artifact.getTimestampString(); } else { maxBuildNumber = Math.max(1, maxBuildNumber); } lastUpdated = Math.max(lastUpdated, content.getLastModified()); found = true; } } if (!snapshotVersions.isEmpty() || found) { Versioning versioning = metadata.getVersioning(); if (versioning == null) { versioning = new Versioning(); } metadata.setGroupId(groupId); metadata.setArtifactId(artifactId); metadata.setVersion(version); try { Maven3.addSnapshotVersions(versioning, snapshotVersions); } catch (LinkageError e) { // Maven 2 } if (maxBuildNumber > 0) { Snapshot snapshot = new Snapshot(); snapshot.setBuildNumber(maxBuildNumber); snapshot.setTimestamp(timestamp); versioning.setSnapshot(snapshot); } versioning.setLastUpdatedTimestamp(new Date(lastUpdated)); metadata.setVersioning(versioning); foundMetadata = true; } } } if (!foundMetadata) { throw new MetadataNotFoundException(path); } return metadata; }
From source file:org.codehaus.mojo.mrm.impl.maven.MockArtifactStore.java
/** * {@inheritDoc}//from w w w. j a va 2 s .co m */ public synchronized long getMetadataLastModified(String path) throws IOException, MetadataNotFoundException { boolean haveResult = false; long result = 0; path = StringUtils.stripEnd(StringUtils.stripStart(path, "/"), "/"); String groupId = path.replace('/', '.'); Map<String, Map<String, Map<Artifact, Content>>> artifactMap = contents.get(groupId); if (artifactMap != null) { for (Map<String, Map<Artifact, Content>> versionMap : artifactMap.values()) { for (Map<Artifact, Content> filesMap : versionMap.values()) { for (Content content : filesMap.values()) { haveResult = true; result = Math.max(result, content.getLastModified()); } } } } int index = path.lastIndexOf('/'); groupId = index == -1 ? groupId : groupId.substring(0, index).replace('/', '.'); String artifactId = (index == -1 ? null : path.substring(index + 1)); if (artifactId != null) { artifactMap = contents.get(groupId); Map<String, Map<Artifact, Content>> versionMap = (artifactMap == null ? null : artifactMap.get(artifactId)); if (versionMap != null) { for (Map<Artifact, Content> filesMap : versionMap.values()) { for (Content content : filesMap.values()) { haveResult = true; result = Math.max(result, content.getLastModified()); } } } } int index2 = index == -1 ? -1 : path.lastIndexOf('/', index - 1); groupId = index2 == -1 ? groupId : groupId.substring(0, index2).replace('/', '.'); artifactId = index2 == -1 ? artifactId : path.substring(index2 + 1, index); String version = index2 == -1 ? null : path.substring(index + 1); if (version != null && version.endsWith("-SNAPSHOT")) { artifactMap = contents.get(groupId); Map<String, Map<Artifact, Content>> versionMap = (artifactMap == null ? null : artifactMap.get(artifactId)); Map<Artifact, Content> filesMap = (versionMap == null ? null : versionMap.get(version)); if (filesMap != null) { for (Content content : filesMap.values()) { haveResult = true; result = Math.max(result, content.getLastModified()); } } } if (haveResult) { return result; } throw new MetadataNotFoundException(path); }
From source file:org.drupal.ModuleInfoParser.java
public void read(File file) throws FileNotFoundException, IOException { String line;//from w w w . jav a 2s.c om BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file))); while ((line = reader.readLine()) != null) { Matcher matcher = pattern.matcher(line); if (matcher.matches()) { List<String> keys; String key = matcher.group(1); String value = matcher.group(2); keys = Arrays.asList(StringUtils.stripStart(key, "]").split("\\]?\\[")); if (!keys.isEmpty()) { ModuleProperty moduleProperty = ModuleProperty.parse(keys.get(0)); if (moduleProperty != null) { IPropertyParser propertyParser = moduleProperty.getParser(this); propertyParser.parse(keys, value); } } } } }
From source file:org.eclipse.wb.internal.core.utils.xml.AbstractDocumentEditContext.java
private void handleNodeMove(DocumentElement element, DocumentElement oldParent, DocumentElement newParent, int index) throws Exception { // remove from old parent // if reorder in same parent, tweak index {// w w w . ja v a 2s. com int oldIndex = oldParent.indexOf(element); oldParent.m_children.remove(element); if (newParent == oldParent && oldIndex < index) { index--; } } // prepare begin of String to move int beginOffset = getElementSourceOffset(element); // extract String from old parent String elementString; { int endOffset = element.getOffset() + element.getLength(); elementString = m_document.get(beginOffset, endOffset - beginOffset); elementString = StringUtils.stripStart(elementString, null); replaceString(beginOffset, endOffset - beginOffset, ""); } // prepare target information ensureElementOpen(newParent); TargetInformation targetInfo = prepareTargetInformation(newParent, index); // insert prefix String prefix = targetInfo.prefix; int newOffset = targetInfo.offset; replaceString(newOffset, 0, prefix); newOffset += prefix.length(); // insert "element" String replaceString(newOffset, 0, elementString); // add into new parent newParent.m_children.add(index, element); element.setParent(newParent); moveElementOffsets(element, newOffset - element.getOffset()); // if last child was moved, then parent should be closed closeIfNoChildren(oldParent); }
From source file:org.ejbca.util.CertTools.java
/** * Creates a (Bouncycastle) X509Name object from a string with a DN. Known OID * (with order) are:/* ww w . jav a 2 s.c o m*/ * <code> EmailAddress, UID, CN, SN (SerialNumber), GivenName, Initials, SurName, T, OU, * O, L, ST, DC, C </code> * To change order edit 'dnObjects' in this source file. Important NOT to mess * with the ordering within this class, since cert vierification on some * clients (IE :-() might depend on order. * * @param dn * String containing DN that will be transformed into X509Name, The * DN string has the format "CN=zz,OU=yy,O=foo,C=SE". Unknown OIDs in * the string will be added to the end positions of OID array. * @param converter BC converter for DirectoryStrings, that determines which encoding is chosen * @param ldaporder true if LDAP ordering of DN should be used (default in EJBCA), false for X.500 order, ldap order is CN=A,OU=B,O=C,C=SE, x.500 order is the reverse * @return X509Name or null if input is null */ public static X509Name stringToBcX509Name(String dn, X509NameEntryConverter converter, boolean ldaporder) { if (dn == null) { return null; } Vector<DERObjectIdentifier> defaultOrdering = new Vector<DERObjectIdentifier>(); Vector<String> values = new Vector<String>(); X509NameTokenizer x509NameTokenizer = new X509NameTokenizer(dn); while (x509NameTokenizer.hasMoreTokens()) { // This is a pair key=val (CN=xx) String pair = x509NameTokenizer.nextToken(); // Will escape '+' and initial '#' chars int index = pair.indexOf('='); if (index != -1) { String key = pair.substring(0, index).toLowerCase().trim(); String val = pair.substring(index + 1); if (val != null) { // String whitespace from the beginning of the value, to handle the case // where someone type CN = Foo Bar val = StringUtils.stripStart(val, null); } // -- First search the OID by name in declared OID's DERObjectIdentifier oid = DnComponents.getOid(key); try { // -- If isn't declared, we try to create it if (oid == null) { oid = new DERObjectIdentifier(key); } defaultOrdering.add(oid); values.add(getUnescapedPlus(val)); } catch (IllegalArgumentException e) { // If it is not an OID we will ignore it log.warn("Unknown DN component ignored and silently dropped: " + key); } } else { log.warn("No 'key=value' pair encountered in token '" + pair + "' while converting subject DN '" + dn + "' into X509Name."); } } X509Name x509Name = new X509Name(defaultOrdering, values, converter); //-- Reorder fields X509Name orderedX509Name = getOrderedX509Name(x509Name, ldaporder, converter); //log.trace("<stringToBcX509Name"); return orderedX509Name; }
From source file:org.geoserver.jdbc.metrics.RequestMetricsController.java
@Override protected ModelAndView handleRequestInternal(HttpServletRequest req, HttpServletResponse rsp) throws Exception { String[] split = req.getPathInfo().split("/"); String reqId = StringUtils.stripEnd(StringUtils.stripStart(split[split.length - 1], "/"), "/"); JSONObject obj = new JSONObject(); obj.put("request", reqId); Map<String, Object> m = METRICS.getIfPresent(reqId); if (m != null) { obj.put("metrics", m); rsp.setStatus(HttpServletResponse.SC_OK); } else {//from w ww . j a v a 2 s . com rsp.setStatus(HttpServletResponse.SC_NOT_FOUND); obj.put("message", "metrics unavailable"); } rsp.setContentType(MediaType.APPLICATION_JSON_VALUE); try (OutputStreamWriter w = new OutputStreamWriter(rsp.getOutputStream(), Charsets.UTF_8)) { obj.write(w); w.flush(); } return null; }
From source file:org.geowebcache.s3.TMSKeyBuilder.java
public String storeMetadata() { return StringUtils.stripStart(String.format(STORE_METADATA_FORMAT, prefix), "/"); }
From source file:org.jahia.services.importexport.ImportExportBaseService.java
/** * Import a full site zip into a newly created site. * <p/>// w w w. jav a2 s . c om * zip file can contain all kind of legacy jahia import files or jcr import format. * * @param file Zip file * @param site The new site where to import * @param infos site infos * @param legacyMappingFilePath path to the legacy mappings * @param legacyDefinitionsFilePath path for the legacy definitions * @param session the current JCR session to use for the import * @throws RepositoryException * @throws IOException */ public void importSiteZip(Resource file, JahiaSite site, Map<Object, Object> infos, Resource legacyMappingFilePath, Resource legacyDefinitionsFilePath, JCRSessionWrapper session) throws RepositoryException, IOException { long timerSite = System.currentTimeMillis(); logger.info("Start import for site {}", site != null ? site.getSiteKey() : ""); final CategoriesImportHandler categoriesImportHandler = new CategoriesImportHandler(); final UsersImportHandler usersImportHandler = new UsersImportHandler(site, session); boolean legacyImport = false; List<String[]> catProps = null; List<String[]> userProps = null; Map<String, Long> sizes = new HashMap<String, Long>(); List<String> fileList = new ArrayList<String>(); logger.info("Start analyzing import file {}", file); long timer = System.currentTimeMillis(); getFileList(file, sizes, fileList); logger.info("Done analyzing import file {} in {}", file, DateUtils.formatDurationWords(System.currentTimeMillis() - timer)); Map<String, String> pathMapping = session.getPathMapping(); for (JahiaTemplatesPackage pkg : templatePackageRegistry.getRegisteredModules().values()) { String key = "/modules/" + pkg.getId() + "/"; if (!pathMapping.containsKey(key)) { pathMapping.put(key, "/modules/" + pkg.getId() + "/" + pkg.getVersion() + "/"); } } ZipInputStream zis; if (sizes.containsKey(USERS_XML)) { // Import users first zis = getZipInputStream(file); try { while (true) { ZipEntry zipentry = zis.getNextEntry(); if (zipentry == null) break; String name = zipentry.getName(); if (name.equals(USERS_XML)) { userProps = importUsers(zis, usersImportHandler); break; } zis.closeEntry(); } } finally { closeInputStream(zis); } } // Check if it is an 5.x or 6.1 import : for (Map.Entry<String, Long> entry : sizes.entrySet()) { if (entry.getKey().startsWith("export_")) { legacyImport = true; break; } } if (sizes.containsKey(SITE_PROPERTIES)) { zis = getZipInputStream(file); try { while (true) { ZipEntry zipentry = zis.getNextEntry(); if (zipentry == null) break; String name = zipentry.getName(); if (name.equals(SITE_PROPERTIES)) { importSiteProperties(zis, site, session); break; } zis.closeEntry(); } } finally { closeInputStream(zis); } } if (sizes.containsKey(REPOSITORY_XML)) { // Parse import file to detect sites zis = getZipInputStream(file); try { while (true) { ZipEntry zipentry = zis.getNextEntry(); if (zipentry == null) break; String name = zipentry.getName(); if (name.equals(REPOSITORY_XML)) { timer = System.currentTimeMillis(); logger.info("Start importing " + REPOSITORY_XML); DocumentViewValidationHandler h = new DocumentViewValidationHandler(); h.setSession(session); List<ImportValidator> validators = new ArrayList<ImportValidator>(); SitesValidator sitesValidator = new SitesValidator(); validators.add(sitesValidator); h.setValidators(validators); handleImport(zis, h, name); Map<String, Properties> sites = ((SitesValidatorResult) sitesValidator.getResult()) .getSitesProperties(); for (String s : sites.keySet()) { // Only the first site returned is mapped (if its not the systemsite, which is always the same key) if (!s.equals("systemsite") && !site.getSiteKey().equals("systemsite")) { // Map to the new sitekey pathMapping.put("/sites/" + s + "/", "/sites/" + site.getSiteKey() + "/"); break; } } if (!sizes.containsKey(SITE_PROPERTIES)) { // todo : site properties can be removed and properties get from here } logger.info("Done importing " + REPOSITORY_XML + " in {}", DateUtils.formatDurationWords(System.currentTimeMillis() - timer)); break; } zis.closeEntry(); } } finally { closeInputStream(zis); } importZip(null, file, DocumentViewImportHandler.ROOT_BEHAVIOUR_IGNORE, session, Sets.newHashSet(USERS_XML, CATEGORIES_XML), true); } else { // No repository descriptor - prepare to import files directly pathMapping.put("/", "/sites/" + site.getSiteKey() + "/files/"); } NodeTypeRegistry reg = NodeTypeRegistry.getInstance(); DefinitionsMapping mapping = null; // Import additional files - site.properties, old cateogries.xml , sitepermissions.xml // and eventual plain file from 5.x imports if (!sizes.containsKey(REPOSITORY_XML) || sizes.containsKey(SITE_PROPERTIES) || sizes.containsKey(CATEGORIES_XML) || sizes.containsKey(SITE_PERMISSIONS_XML) || sizes.containsKey(DEFINITIONS_CND) || sizes.containsKey(DEFINITIONS_MAP)) { zis = getZipInputStream(file); try { while (true) { ZipEntry zipentry = zis.getNextEntry(); if (zipentry == null) break; String name = zipentry.getName(); if (name.indexOf('\\') > -1) { name = name.replace('\\', '/'); } if (name.indexOf('/') > -1) { if (!sizes.containsKey(REPOSITORY_XML) && !sizes.containsKey(FILESACL_XML)) { // No repository descriptor - Old import format only name = "/" + name; if (name.startsWith("/content/sites")) { name = pathMapping.get("/") + StringUtils .stripStart(name.replaceFirst("/content/sites/[^/]+/files/", ""), "/"); } else if (name.startsWith("/users")) { Matcher m = Pattern.compile("/users/([^/]+)(/.*)?").matcher(name); if (m.matches()) { name = ServicesRegistry.getInstance().getJahiaUserManagerService() .getUserSplittingRule().getPathForUsername(m.group(1)); name = name + "/files" + ((m.group(2) != null) ? m.group(2) : ""); } } else if (name.startsWith("/content/users")) { Matcher m = Pattern.compile("/content/users/([^/]+)(/.*)?").matcher(name); if (m.matches()) { name = ServicesRegistry.getInstance().getJahiaUserManagerService() .getUserSplittingRule().getPathForUsername(m.group(1)); name = name + ((m.group(2) != null) ? m.group(2) : ""); } } else { name = pathMapping.get("/") + StringUtils.stripStart(name, "/"); } if (!zipentry.isDirectory()) { try { String filename = name.substring(name.lastIndexOf('/') + 1); ensureFile(session, name, zis, JCRContentUtils.getMimeType(filename), site); } catch (Exception e) { logger.error("Cannot upload file " + zipentry.getName(), e); } } else { ensureDir(session, name, site); } } } else if (name.equals(CATEGORIES_XML)) { catProps = importCategoriesAndGetUuidProps(zis, categoriesImportHandler); } else if (name.equals(DEFINITIONS_CND)) { reg = new NodeTypeRegistry(); // this is fishy: a new instance is created here when NodeTypeRegistry is meant to be used as a singleton try { for (Map.Entry<String, File> entry : NodeTypeRegistry.getSystemDefinitionsFiles() .entrySet()) { reg.addDefinitionsFile(entry.getValue(), entry.getKey()); } if (legacyImport) { JahiaCndReaderLegacy r = new JahiaCndReaderLegacy( new InputStreamReader(zis, Charsets.UTF_8), zipentry.getName(), file.getURL().getPath(), reg); r.parse(); } else { reg.addDefinitionsFile(new InputStreamResource(zis, zipentry.getName()), file.getURL().getPath()); } } catch (RepositoryException | ParseException e) { logger.error(e.getMessage(), e); } } else if (name.equals(DEFINITIONS_MAP)) { mapping = new DefinitionsMapping(); mapping.load(zis); } zis.closeEntry(); } } finally { closeInputStream(zis); } } // Import legacy content from 5.x and 6.x if (legacyImport) { long timerLegacy = System.currentTimeMillis(); final String originatingJahiaRelease = (String) infos.get("originatingJahiaRelease"); logger.info("Start legacy import, source version is " + originatingJahiaRelease); if (legacyMappingFilePath != null) { mapping = new DefinitionsMapping(); final InputStream fileInputStream = legacyMappingFilePath.getInputStream(); try { mapping.load(fileInputStream); } finally { IOUtils.closeQuietly(fileInputStream); } } if (legacyDefinitionsFilePath != null) { reg = new NodeTypeRegistry(); if ("6.1".equals(originatingJahiaRelease)) { logger.info("Loading the built in 6.1 definitions before processing the provided custom ones"); final List<String> builtInLegacyDefs = Arrays.asList("01-system-nodetypes.cnd", "02-jahiacore-nodetypes.cnd", "03-files-nodetypes.cnd", "04-jahiacontent-nodetypes.cnd", "05-standard-types.cnd", "10-extension-nodetypes.cnd", "11-preferences-nodetypes.cnd"); for (String builtInLegacyDefsFile : builtInLegacyDefs) { InputStreamReader inputStreamReader = null; try { final InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream( "org/jahia/migration/legacyDefinitions/jahia6/" + builtInLegacyDefsFile); if (inputStream != null) { inputStreamReader = new InputStreamReader(inputStream, "UTF-8"); final JahiaCndReaderLegacy r = new JahiaCndReaderLegacy(inputStreamReader, builtInLegacyDefsFile, file.getURL().getPath(), reg); r.parse(); } else { logger.error("Couldn't load " + builtInLegacyDefsFile); } } catch (ParseException e) { logger.error(e.getMessage(), e); } finally { IOUtils.closeQuietly(inputStreamReader); } } } else { try { for (Map.Entry<String, File> entry : NodeTypeRegistry.getSystemDefinitionsFiles() .entrySet()) { reg.addDefinitionsFile(entry.getValue(), entry.getKey()); } } catch (ParseException e) { logger.error("Cannot parse definitions : " + e.getMessage(), e); } } InputStreamReader streamReader = null; try { streamReader = new InputStreamReader(legacyDefinitionsFilePath.getInputStream(), "UTF-8"); JahiaCndReaderLegacy r = new JahiaCndReaderLegacy(streamReader, legacyDefinitionsFilePath.getFilename(), file.getURL().getPath(), reg); r.parse(); } catch (ParseException e) { logger.error(e.getMessage(), e); } finally { IOUtils.closeQuietly(streamReader); } } // Old import JCRNodeWrapper siteFolder = session.getNode("/sites/" + site.getSiteKey()); zis = new NoCloseZipInputStream(new BufferedInputStream(file.getInputStream())); try { int legacyImportHandlerCtnId = 1; while (true) { ZipEntry zipentry = zis.getNextEntry(); if (zipentry == null) break; String name = zipentry.getName(); if (name.equals(FILESACL_XML)) { logger.info("Importing file " + FILESACL_XML); importFilesAcl(site, file, zis, mapping, fileList); } else if (name.startsWith("export")) { logger.info("Importing file " + name); String languageCode; if (name.indexOf("_") != -1) { languageCode = name.substring(7, name.lastIndexOf(".")); } else { languageCode = site.getLanguagesAsLocales().iterator().next().toString(); } zipentry.getSize(); LegacyImportHandler importHandler = new LegacyImportHandler(session, siteFolder, reg, mapping, LanguageCodeConverters.languageCodeToLocale(languageCode), infos != null ? originatingJahiaRelease : null, legacyPidMappingTool, legacyImportHandlerCtnId); Map<String, List<String>> references = new LinkedHashMap<String, List<String>>(); importHandler.setReferences(references); InputStream documentInput = zis; if (this.xmlContentTransformers != null && this.xmlContentTransformers.size() > 0) { documentInput = new ZipInputStream(file.getInputStream()); while (!name.equals(((ZipInputStream) documentInput).getNextEntry().getName())) ; byte[] buffer = new byte[2048]; final File tmpDirectoryForSite = new File( new File(System.getProperty("java.io.tmpdir"), "jahia-migration"), FastDateFormat.getInstance("yyyy_MM_dd-HH_mm_ss_SSS").format(timerSite) + "_" + site.getSiteKey()); tmpDirectoryForSite.mkdirs(); File document = new File(tmpDirectoryForSite, "export_" + languageCode + "_00_extracted.xml"); final OutputStream output = new BufferedOutputStream(new FileOutputStream(document), 2048); int count = 0; while ((count = documentInput.read(buffer, 0, 2048)) > 0) { output.write(buffer, 0, count); } output.flush(); output.close(); documentInput.close(); for (XMLContentTransformer xct : xmlContentTransformers) { document = xct.transform(document, tmpDirectoryForSite); } documentInput = new FileInputStream(document); } handleImport(documentInput, importHandler, name); legacyImportHandlerCtnId = importHandler.getCtnId(); ReferencesHelper.resolveCrossReferences(session, references); siteFolder.getSession().save(JCRObservationManager.IMPORT); } zis.closeEntry(); } ReferencesHelper.resolveReferencesKeeper(session); siteFolder.getSession().save(JCRObservationManager.IMPORT); } finally { closeInputStream(zis); } logger.info("Done legacy import in {}", DateUtils.formatDurationWords(System.currentTimeMillis() - timerLegacy)); } categoriesImportHandler.setUuidProps(catProps); usersImportHandler.setUuidProps(userProps); // session.save(); session.save(JCRObservationManager.IMPORT); cleanFilesList(fileList); if (legacyImport && this.postImportPatcher != null) { final long timerPIP = System.currentTimeMillis(); logger.info("Executing post import patches"); this.postImportPatcher.executePatches(site); logger.info("Executed post import patches in {}", DateUtils.formatDurationWords(System.currentTimeMillis() - timerPIP)); } logger.info("Done importing site {} in {}", site != null ? site.getSiteKey() : "", DateUtils.formatDurationWords(System.currentTimeMillis() - timerSite)); }
From source file:org.jamwiki.parser.jflex.JFlexLexer.java
/** * *//* w w w .j a v a2 s . co m*/ protected void parseParagraphStart(String raw) { int pushback = raw.length(); if (this.mode >= JFlexParser.MODE_LAYOUT) { this.pushTag("p", null); int newlineCount = StringUtils.countMatches(raw, "\n"); if (newlineCount > 0) { pushback = StringUtils.stripStart(raw, " \n\r\t").length(); } if (newlineCount == 2) { // if the pattern matched two opening newlines then start the paragraph with a <br /> tag this.append("<br />\n"); } } yypushback(pushback); }