下面列出了org.apache.http.impl.conn.SystemDefaultRoutePlanner#org.apache.ivy.util.Message 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public void unpack(InputStream packed, File dest) throws IOException {
try (ZipInputStream zip = new ZipInputStream(packed)) {
ZipEntry entry = null;
while (((entry = zip.getNextEntry()) != null)) {
File f = new File(dest, entry.getName());
Message.verbose("\t\texpanding " + entry.getName() + " to " + f);
// create intermediary directories - sometimes zip don't add them
File dirF = f.getParentFile();
if (dirF != null) {
dirF.mkdirs();
}
if (entry.isDirectory()) {
f.mkdirs();
} else {
writeFile(zip, f);
}
f.setLastModified(entry.getTime());
}
}
}
@Override
public void log(String message, int level) {
message = "[Ivy] " + message.trim();
switch (level) {
case Message.MSG_ERR:
JkLog.error(message);
break;
case Message.MSG_WARN:
JkLog.warn(message);
break;
case Message.MSG_INFO:
JkLog.info(message);
break;
case Message.MSG_VERBOSE:
JkLog.trace(message);
break;
case Message.MSG_DEBUG:
if (JkLog.Verbosity.QUITE_VERBOSE.equals(JkLog.verbosity())) {
JkLog.trace(message);
}
break;
default:
JkLog.info("[" + level + "] " + message);
}
}
private boolean checkStatusCode(URL url, HttpURLConnection con) throws IOException {
final int status = con.getResponseCode();
if (status == HttpStatus.SC_OK) {
return true;
}
// IVY-1328: some servers return a 204 on a HEAD request
if ("HEAD".equals(con.getRequestMethod()) && (status == 204)) {
return true;
}
Message.debug("HTTP response status: " + status + " url=" + url);
if (status == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) {
Message.warn("Your proxy requires authentication.");
} else if (String.valueOf(status).startsWith("4")) {
Message.verbose("CLIENT ERROR: " + con.getResponseMessage() + " url=" + url);
} else if (String.valueOf(status).startsWith("5")) {
Message.error("SERVER ERROR: " + con.getResponseMessage() + " url=" + url);
}
return false;
}
public void saveResolvedRevision(String resolverName, ModuleRevisionId mrid, String revision) {
if (!lockMetadataArtifact(mrid)) {
Message.error("impossible to acquire lock for " + mrid);
return;
}
try {
PropertiesFile cachedResolvedRevision;
if (resolverName == null) {
cachedResolvedRevision = getCachedDataFile(mrid);
} else {
cachedResolvedRevision = getCachedDataFile(resolverName, mrid);
}
cachedResolvedRevision.setProperty("resolved.time",
String.valueOf(System.currentTimeMillis()));
cachedResolvedRevision.setProperty("resolved.revision", revision);
if (resolverName != null) {
cachedResolvedRevision.setProperty("resolver", resolverName);
}
cachedResolvedRevision.save();
} finally {
unlockMetadataArtifact(mrid);
}
}
/**
* Get a list of direct descendants of the given resource. Note that attempts to get a list of
* children does <em>not</em> result in an error. Instead an error message is
* logged and an empty ArrayList returned.
*
* @return A <code>ArrayList</code> of VFSResources
*/
public List<String> getChildren() {
init();
List<String> list = new ArrayList<>();
try {
if (resourceImpl != null && resourceImpl.exists()
&& resourceImpl.getType() == FileType.FOLDER) {
for (FileObject child : resourceImpl.getChildren()) {
list.add(normalize(child.getName().getURI()));
}
}
} catch (IOException e) {
Message.debug(e);
Message.verbose(e.getLocalizedMessage());
}
return list;
}
@Before
public void setUp() throws Exception {
Message.setDefaultLogger(new DefaultMessageLogger(99));
settings = new IvySettings();
ResolveEngine engine = new ResolveEngine(settings, new EventManager(), new SortEngine(
settings));
cache = new File("build/cache");
data = new ResolveData(engine, new ResolveOptions());
cache.mkdirs();
settings.setDefaultCache(cache);
// Create work space with build and resource cache directories
workdir = new File("build/test/PackagerResolverTest");
builddir = new File(workdir, "build");
cachedir = new File(workdir, "resources");
cleanupTempDirs();
if (!builddir.mkdirs() || !cachedir.mkdirs()) {
throw new Exception("can't create directories under " + workdir);
}
}
public void output(ConfigurationResolveReport report, String resolveId, String[] confs,
ResolutionCacheManager cacheMgr) throws IOException {
File reportFile = cacheMgr.getConfigurationResolveReportInCache(resolveId,
report.getConfiguration());
File reportParentDir = reportFile.getParentFile();
reportParentDir.mkdirs();
OutputStream stream = new FileOutputStream(reportFile);
writer.output(report, confs, stream);
stream.close();
Message.verbose("\treport for " + report.getModuleDescriptor().getModuleRevisionId() + " "
+ report.getConfiguration() + " produced in " + reportFile);
File reportXsl = new File(reportParentDir, "ivy-report.xsl");
File reportCss = new File(reportParentDir, "ivy-report.css");
if (!reportXsl.exists()) {
FileUtil.copy(XmlReportOutputter.class.getResourceAsStream("ivy-report.xsl"),
reportXsl, null);
}
if (!reportCss.exists()) {
FileUtil.copy(XmlReportOutputter.class.getResourceAsStream("ivy-report.css"),
reportCss, null);
}
}
void putInCache(File url, ParserSettingsMonitor ivySettingsMonitor, boolean validated,
ModuleDescriptor descriptor) {
if (maxSize <= 0) {
// cache is disabled
return;
}
synchronized (valueMap) {
if (valueMap.size() >= maxSize) {
Message.debug("ModuleDescriptorCache is full, remove one entry");
Iterator<CacheEntry> it = valueMap.values().iterator();
it.next();
it.remove();
}
valueMap.put(url, new CacheEntry(descriptor, validated, ivySettingsMonitor));
}
}
public boolean tryLock(File file) {
try {
if (file.getParentFile().exists() || file.getParentFile().mkdirs()) {
if (file.createNewFile()) {
DeleteOnExitHook.add(file);
return true;
} else {
if (debugLocking) {
debugLocking("file creation failed " + file);
}
}
}
} catch (IOException e) {
// ignored
Message.verbose("file creation failed due to an exception: " + e.getMessage()
+ " (" + file + ")");
}
return false;
}
/**
* used to copy a module descriptor xml file (also known as ivy file) and update the revisions
* of its dependencies, its status and revision
*
* @param srcURL
* the url of the source module descriptor file
* @param destFile
* The file to which the updated module descriptor should be output
* @param options
* UpdateOptions
* @throws IOException if something goes wrong
* @throws SAXException if something goes wrong
*/
public static void update(URL srcURL, File destFile, UpdateOptions options) throws IOException,
SAXException {
if (destFile.getParentFile() != null) {
destFile.getParentFile().mkdirs();
}
OutputStream destStream = new FileOutputStream(destFile);
try {
update(srcURL, destStream, options);
} finally {
try {
destStream.close();
} catch (IOException e) {
Message.warn("failed to close a stream : " + e.toString());
}
}
}
@Before
public void setUp() throws Exception {
File f = File.createTempFile("ivycache", ".dir");
ivy = new Ivy();
ivy.configureDefault();
ivy.getLoggerEngine().setDefaultLogger(new DefaultMessageLogger(Message.MSG_DEBUG));
IvyContext.pushNewContext().setIvy(ivy);
IvySettings settings = ivy.getSettings();
f.delete(); // we want to use the file as a directory, so we delete the file itself
cacheManager = new DefaultRepositoryCacheManager();
cacheManager.setSettings(settings);
cacheManager.setBasedir(f);
artifact = createArtifact("org", "module", "rev", "name", "type", "ext");
Artifact originArtifact = createArtifact("org", "module", "rev", "name", "pom.original",
"pom");
origin = new ArtifactOrigin(originArtifact, true, "file:/some/where.pom");
cacheManager.saveArtifactOrigin(originArtifact, origin);
cacheManager.saveArtifactOrigin(artifact, origin);
}
public static void adapt(BundleInfo bundleInfo, Capability capability) throws ParseException {
String name = capability.getName();
switch (name) {
case BundleInfo.PACKAGE_TYPE:
bundleInfo.addCapability(getExportPackage(bundleInfo, capability));
break;
case BundleInfo.BUNDLE_TYPE:
// nothing to do, already handled at the resource tag level
break;
case BundleInfo.SERVICE_TYPE:
bundleInfo.addCapability(getOSGiService(bundleInfo, capability));
break;
default:
Message.warn("Unsupported capability '" + name + "' on the bundle '"
+ bundleInfo.getSymbolicName() + "'");
break;
}
}
@Override
protected void handleAttributes(Attributes atts) throws SAXException {
String symbolicname = atts.getValue(SYMBOLIC_NAME);
if (symbolicname == null) {
log(Message.MSG_ERR, "Resource with no symbolic name, skipping it.");
skip();
return;
}
String v = getOptionalAttribute(atts, VERSION, DEFAULT_VERSION);
Version version = new Version(v);
bundleInfo = new BundleInfo(symbolicname, version);
bundleInfo.setPresentationName(atts.getValue(PRESENTATION_NAME));
String uri = atts.getValue(URI);
if (uri != null) {
try {
bundleInfo.addArtifact(new BundleArtifact(false, new URI(uri), null));
} catch (URISyntaxException e) {
log(Message.MSG_ERR, "Incorrect uri " + uri + ". The resource " + symbolicname
+ " is then ignored.");
skip();
return;
}
}
bundleInfo.setId(atts.getValue(ID));
}
@Test
public void testRetrieveSameFileConflict() throws Exception {
// mod1.1 depends on mod1.2
ResolveReport report = ivy.resolve(new File(
"test/repositories/1/org1/mod1.4/ivys/ivy-1.0.1.xml").toURI().toURL(),
getResolveOptions(new String[] {"*"}));
assertNotNull(report);
ModuleDescriptor md = report.getModuleDescriptor();
assertNotNull(md);
String pattern = "build/test/retrieve/[module]/[artifact]-[revision].[ext]";
MockMessageLogger mockLogger = new MockMessageLogger();
Message.setDefaultLogger(mockLogger);
ivy.retrieve(md.getModuleRevisionId(),
getRetrieveOptions().setDestArtifactPattern(pattern));
assertTrue(new File(IvyPatternHelper.substitute(pattern, "org1", "mod1.2", "2.2", "mod1.2",
"jar", "jar", "default")).exists());
mockLogger.assertLogDoesntContain("conflict on");
}
/**
* Parses a ls -l line and transforms it in a resource
*
* @param file ditto
* @param responseLine ditto
* @return Resource
*/
protected Resource lslToResource(String file, String responseLine) {
if (responseLine == null || responseLine.startsWith("ls")) {
return new BasicResource(file, false, 0, 0, false);
} else {
String[] parts = responseLine.split("\\s+");
if (parts.length != LS_PARTS_NUMBER) {
Message.debug("unrecognized ls format: " + responseLine);
return new BasicResource(file, false, 0, 0, false);
} else {
try {
long contentLength = Long.parseLong(parts[LS_SIZE_INDEX]);
String date = parts[LS_DATE_INDEX1] + " " + parts[LS_DATE_INDEX2] + " "
+ parts[LS_DATE_INDEX3] + " " + parts[LS_DATE_INDEX4];
return new BasicResource(file, true, contentLength, FORMAT.parse(date)
.getTime(), false);
} catch (Exception ex) {
Message.warn("impossible to parse server response: " + responseLine, ex);
return new BasicResource(file, false, 0, 0, false);
}
}
}
}
public void analyse(String pattern, DependencyAnalyser depAnalyser) {
JarModuleFinder finder = new JarModuleFinder(pattern);
ModuleDescriptor[] mds = depAnalyser.analyze(finder.findJarModules());
Message.info("found " + mds.length + " modules");
for (ModuleDescriptor md : mds) {
File ivyFile = new File(IvyPatternHelper.substitute(
pattern,
DefaultArtifact.newIvyArtifact(md.getModuleRevisionId(),
md.getPublicationDate())));
try {
Message.info("generating " + ivyFile);
XmlModuleDescriptorWriter.write(md, ivyFile);
} catch (IOException e) {
Message.debug(e);
}
}
}
/**
* If current module has already been added to list, returns, Otherwise invokes
* sortModuleDescriptorsHelp for all dependencies contained within set of moduleDescriptors.
* Then finally adds self to list of sorted.<br/>
* When a loop is detected by a recursive call, the moduleDescriptors are not added immediately
* added to the sorted list. They are added as loop dependencies of the root, and will be added
* to the sorted list only when the root itself will be added.
*
* @param current
* Current module to add to sorted list.
* @throws CircularDependencyException somehow
*/
private void sortModuleDescriptorsHelp(ModuleInSort current, ModuleInSort caller)
throws CircularDependencyException {
// if already sorted return
if (current.isProcessed()) {
return;
}
if (current.checkLoop(caller, circularDepStrategy)) {
return;
}
DependencyDescriptor[] descriptors = current.getDependencies();
Message.debug("Sort dependencies of : " + current.toString()
+ " / Number of dependencies = " + descriptors.length);
current.setCaller(caller);
for (DependencyDescriptor descriptor : descriptors) {
ModuleInSort child = moduleDescriptors.getModuleDescriptorDependency(descriptor);
if (child != null) {
sortModuleDescriptorsHelp(child, current);
}
}
current.endOfCall();
Message.debug("Sort done for : " + current.toString());
current.addToSortedListIfRequired(sorted);
}
public static String[] listAll(URLLister lister, URL root) {
try {
if (lister.accept(root.toExternalForm())) {
Message.debug("\tusing " + lister + " to list all in " + root);
List<URL> all = lister.listAll(root);
Message.debug("\t\tfound " + all.size() + " urls");
List<String> names = new ArrayList<>(all.size());
for (URL dir : all) {
String path = dir.getPath();
if (path.endsWith("/")) {
path = path.substring(0, path.length() - 1);
}
int slashIndex = path.lastIndexOf('/');
names.add(path.substring(slashIndex + 1));
}
return names.toArray(new String[names.size()]);
}
return null;
} catch (Exception e) {
Message.warn("problem while listing directories in " + root, e);
return null;
}
}
private void resolveAndCheckRevision(ModuleDescriptor systemMd,
ModuleRevisionId dependencyConstraint, ResolvedResource ivyRef, boolean isDynamic) {
// we get the resolved module revision id from the descriptor: it may contain extra
// attributes that were not included in the dependency constraint
ModuleRevisionId resolvedMrid = systemMd.getResolvedModuleRevisionId();
if (resolvedMrid.getRevision() == null || resolvedMrid.getRevision().length() == 0
|| resolvedMrid.getRevision().startsWith("[email protected]")) {
if (!isDynamic) {
resolvedMrid = ModuleRevisionId.newInstance(resolvedMrid,
dependencyConstraint.getRevision());
} else if (ivyRef == null) {
resolvedMrid = systemMd.getMetadataArtifact().getModuleRevisionId();
} else if (ivyRef.getRevision() == null || ivyRef.getRevision().length() == 0) {
resolvedMrid = ModuleRevisionId.newInstance(resolvedMrid, "[email protected]" + getName());
} else {
resolvedMrid = ModuleRevisionId.newInstance(resolvedMrid, ivyRef.getRevision());
}
}
if (isDynamic) {
Message.verbose("\t\t[" + toSystem(resolvedMrid).getRevision() + "] "
+ dependencyConstraint.getModuleId());
}
systemMd.setResolvedModuleRevisionId(resolvedMrid);
checkModuleDescriptorRevision(systemMd, dependencyConstraint);
}
private boolean checkStatusCode(URL url, HttpURLConnection con) throws IOException {
int status = con.getResponseCode();
if (status == HttpStatus.SC_OK) {
return true;
}
// IVY-1328: some servers return a 204 on a HEAD request
if ("HEAD".equals(con.getRequestMethod()) && (status == 204)) {
return true;
}
Message.debug("HTTP response status: " + status + " url=" + url);
if (status == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) {
Message.warn("Your proxy requires authentication.");
} else if (String.valueOf(status).startsWith("4")) {
Message.verbose("CLIENT ERROR: " + con.getResponseMessage() + " url=" + url);
} else if (String.valueOf(status).startsWith("5")) {
Message.error("SERVER ERROR: " + con.getResponseMessage() + " url=" + url);
}
return false;
}
private boolean checkStatusCode(final String httpMethod, final URL sourceURL, final HttpResponse response) {
final int status = response.getStatusLine().getStatusCode();
if (status == HttpStatus.SC_OK) {
return true;
}
// IVY-1328: some servers return a 204 on a HEAD request
if (HttpHead.METHOD_NAME.equals(httpMethod) && (status == 204)) {
return true;
}
Message.debug("HTTP response status: " + status + " url=" + sourceURL);
if (status == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) {
Message.warn("Your proxy requires authentication.");
} else if (String.valueOf(status).startsWith("4")) {
Message.verbose("CLIENT ERROR: " + response.getStatusLine().getReasonPhrase() + " url=" + sourceURL);
} else if (String.valueOf(status).startsWith("5")) {
Message.error("SERVER ERROR: " + response.getStatusLine().getReasonPhrase() + " url=" + sourceURL);
}
return false;
}
/**
* Resolve dependencies of a module described by an ivy file.
*
* @param ivySource URL
* @param options ResolveOptions
* @return ResolveReport
* @throws ParseException if something goes wrong
* @throws IOException if something goes wrong
*/
public ResolveReport resolve(URL ivySource, ResolveOptions options) throws ParseException,
IOException {
URLResource res = new URLResource(ivySource);
ModuleDescriptorParser parser = ModuleDescriptorParserRegistry.getInstance().getParser(res);
Message.verbose("using " + parser + " to parse " + ivySource);
ModuleDescriptor md = parser.parseDescriptor(settings, ivySource, options.isValidate());
String revision = options.getRevision();
if (revision == null && md.getResolvedModuleRevisionId().getRevision() == null) {
revision = Ivy.getWorkingRevision();
}
if (revision != null) {
md.setResolvedModuleRevisionId(ModuleRevisionId.newInstance(md.getModuleRevisionId(),
revision));
}
return resolve(md, options);
}
protected void ivyModuleStarted(Attributes attributes) throws SAXException {
descriptorVersion = attributes.getValue("version");
int versionIndex = ALLOWED_VERSIONS.indexOf(descriptorVersion);
if (versionIndex == -1) {
addError("invalid version " + descriptorVersion);
throw new SAXException("invalid version " + descriptorVersion);
}
if (versionIndex >= ALLOWED_VERSIONS.indexOf("1.3")) {
Message.debug("post 1.3 ivy file: using " + PatternMatcher.EXACT
+ " as default matcher");
defaultMatcher = settings.getMatcher(PatternMatcher.EXACT);
} else {
Message.debug("pre 1.3 ivy file: using " + PatternMatcher.EXACT_OR_REGEXP
+ " as default matcher");
defaultMatcher = settings.getMatcher(PatternMatcher.EXACT_OR_REGEXP);
}
for (int i = 0; i < attributes.getLength(); i++) {
if (attributes.getQName(i).startsWith("xmlns:")) {
getMd().addExtraAttributeNamespace(
attributes.getQName(i).substring("xmlns:".length()), attributes.getValue(i));
}
}
}
@Deprecated
public void discardConf(String rootModuleConf, String conf) {
Set<String> depConfs = usage.addAndGetConfigurations(rootModuleConf);
if (md == null) {
depConfs.remove(conf);
} else {
// remove all given dependency configurations to the set + extended ones
Configuration c = md.getConfiguration(conf);
if (conf == null) {
Message.warn("unknown configuration in " + getId() + ": " + conf);
} else {
// recursive remove of extended configurations
for (String ext : c.getExtends()) {
discardConf(rootModuleConf, ext);
}
depConfs.remove(c.getName());
}
}
}
private Class<?> classForName(String className, boolean silentFail) {
try {
return getClassLoader().loadClass(className);
} catch (ClassNotFoundException e) {
if (silentFail) {
Message.info("impossible to define new type: class not found: " + className
+ " in " + classpathURLs + " nor Ivy classloader");
return null;
} else {
throw new RuntimeException("impossible to define new type: class not found: "
+ className + " in " + classpathURLs + " nor Ivy classloader");
}
}
}
/**
* Return a flag indicating whether a provided VFS resource physically exists
*
* @return <code>true</code> if the resource physically exists, <code>false</code> otherwise.
*/
public boolean physicallyExists() {
// TODO: there is no need for this method anymore, replace it by calling exists();
init();
try {
return resourceImpl.exists();
// originally I only checked for a FileSystemException. I expanded it to
// include all exceptions when I found it would throw a NPE exception when the query was
// run on ill-formed VFS URI.
} catch (Exception e) {
Message.verbose("Fail to check the existence of the resource " + getName(), e);
return false;
}
}
public Ivy configure() throws Exception {
boolean verbose = System.getProperty("verbose") != null;
boolean debug = System.getProperty("debug") != null;
HumanReadyLogger humanReadyLogger = new HumanReadyLogger();
IvySettings ivySettings = new IvySettings();
new SettingsParser(humanReadyLogger).parse(ivySettings, new File(framework, "framework/dependencies.yml"));
new SettingsParser(humanReadyLogger).parse(ivySettings, new File(application, "conf/dependencies.yml"));
ivySettings.setDefaultResolver("mavenCentral");
ivySettings.setDefaultUseOrigin(true);
PlayConflictManager conflictManager = new PlayConflictManager();
ivySettings.addConflictManager("playConflicts", conflictManager);
ivySettings.addConflictManager("defaultConflicts", conflictManager.deleguate);
ivySettings.setDefaultConflictManager(conflictManager);
Ivy ivy = Ivy.newInstance(ivySettings);
// Default ivy config see: http://play.lighthouseapp.com/projects/57987-play-framework/tickets/807
File ivyDefaultSettings = new File(userHome, ".ivy2/ivysettings.xml");
if(ivyDefaultSettings.exists()) {
ivy.configure(ivyDefaultSettings);
}
if (debug) {
ivy.getLoggerEngine().pushLogger(new DefaultMessageLogger(Message.MSG_DEBUG));
} else if (verbose) {
ivy.getLoggerEngine().pushLogger(new DefaultMessageLogger(Message.MSG_INFO));
} else {
logger = humanReadyLogger;
ivy.getLoggerEngine().setDefaultLogger(logger);
}
ivy.pushContext();
return ivy;
}
/**
* check for existence of file or dir on target system
*
* @param filePath
* to the object to check
* @param session
* to use
* @return true: object exists, false otherwise
*/
private boolean checkExistence(String filePath, Session session) throws IOException {
Message.debug("SShRepository: checkExistence called: " + filePath);
ChannelExec channel = null;
channel = getExecChannel(session);
String fullCmd = replaceArgument(existCommand, filePath);
channel.setCommand(fullCmd);
StringBuilder stdOut = new StringBuilder();
StringBuilder stdErr = new StringBuilder();
readSessionOutput(channel, stdOut, stdErr);
return channel.getExitStatus() == 0;
}
private void loadModuleRevision(ModuleRevisionId mrid) throws Exception {
ResolvedModuleRevision module = settings.getResolver(mrid).getDependency(
new DefaultDependencyDescriptor(mrid, false), newResolveData());
if (module == null) {
Message.warn("module not found while listed: " + mrid);
} else {
revisions.put(module.getId(), module.getDescriptor());
getAllRevisions(module.getId()).add(module.getDescriptor());
}
Message.progress();
}
protected IvyResolve setupResolve(boolean haltOnFailure, boolean useOrigin) {
Message.verbose("no resolved descriptor found: launching default resolve");
resolve.setTaskName(getTaskName());
resolve.setProject(getProject());
resolve.setHaltonfailure(haltOnFailure);
resolve.setUseOrigin(useOrigin);
resolve.setValidate(doValidate(getSettings()));
resolve.setKeep(isKeep());
resolve.setRefresh(isRefresh());
resolve.setLog(getLog());
resolve.setSettingsRef(getSettingsRef());
resolve.setResolveMode(getResolveMode());
return resolve;
}