use of org.apache.naming.resources.Resource in project Payara by payara.
the class DefaultServlet method doPut.
/**
* Process a POST request for the specified resource.
*
* @param req The servlet request we are processing
* @param resp The servlet response we are creating
*
* @exception IOException if an input/output error occurs
* @exception ServletException if a servlet-specified error occurs
*/
@Override
protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
if (readOnly) {
resp.sendError(HttpServletResponse.SC_FORBIDDEN);
return;
}
String path = getRelativePath(req);
boolean exists = true;
try {
resources.lookup(path);
} catch (NamingException e) {
exists = false;
}
boolean result = true;
// Temp. content file used to support partial PUT
File contentFile = null;
Range range = parseContentRange(req, resp);
InputStream resourceInputStream = null;
// Assume just one range is specified for now
if (range != null) {
contentFile = executePartialPut(req, range, path);
resourceInputStream = new FileInputStream(contentFile);
} else {
resourceInputStream = req.getInputStream();
}
try {
Resource newResource = new Resource(resourceInputStream);
// FIXME: Add attributes
if (exists) {
resources.rebind(path, newResource);
} else {
resources.bind(path, newResource);
}
} catch (NamingException e) {
result = false;
}
if (result) {
if (exists) {
resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
} else {
resp.setStatus(HttpServletResponse.SC_CREATED);
}
} else {
resp.sendError(HttpServletResponse.SC_CONFLICT);
}
}
use of org.apache.naming.resources.Resource in project Payara by payara.
the class DefaultServlet method getReadme.
/**
* Get the readme file as a string.
*/
protected String getReadme(DirContext directory) throws IOException, ServletException {
if (readmeFile != null) {
try {
Object obj = directory.lookup(readmeFile);
if (obj != null && obj instanceof Resource) {
StringWriter buffer = new StringWriter();
InputStream is = ((Resource) obj).streamContent();
copyRange(new InputStreamReader(is), new PrintWriter(buffer));
return buffer.toString();
}
} catch (Throwable e) {
;
/* Should only be IOException or NamingException
* can be ignored
*/
if (debug > 10)
log("readme '" + readmeFile + "' not found", e);
}
}
return null;
}
use of org.apache.naming.resources.Resource in project Payara by payara.
the class WebappLoader method copyDir.
/**
* Copy directory.
*/
private boolean copyDir(DirContext srcDir, File destDir) {
try {
NamingEnumeration<NameClassPair> enumeration = srcDir.list("");
while (enumeration.hasMoreElements()) {
NameClassPair ncPair = enumeration.nextElement();
String name = ncPair.getName();
Object object = srcDir.lookup(name);
File currentFile = new File(destDir, name);
if (object instanceof Resource) {
InputStream is = ((Resource) object).streamContent();
OutputStream os = new FileOutputStream(currentFile);
if (!copy(is, os))
return false;
} else if (object instanceof InputStream) {
OutputStream os = new FileOutputStream(currentFile);
if (!copy((InputStream) object, os))
return false;
} else if (object instanceof DirContext) {
if (!currentFile.isDirectory() && !currentFile.mkdir())
return false;
if (!copyDir((DirContext) object, currentFile))
return false;
}
}
} catch (NamingException | IOException e) {
return false;
}
return true;
}
use of org.apache.naming.resources.Resource in project tomcat70 by apache.
the class ApplicationContext method getResourceAsStream.
/**
* Return the requested resource as an <code>InputStream</code>. The
* path must be specified according to the rules described under
* <code>getResource</code>. If no such resource can be identified,
* return <code>null</code>.
*
* @param path The path to the desired resource.
*/
@Override
public InputStream getResourceAsStream(String path) {
if (path == null)
return (null);
if (!path.startsWith("/") && GET_RESOURCE_REQUIRE_SLASH)
return null;
String normalizedPath = RequestUtil.normalize(path);
if (normalizedPath == null)
return (null);
DirContext resources = context.getResources();
if (resources != null) {
try {
Object resource = resources.lookup(normalizedPath);
if (resource instanceof Resource)
return (((Resource) resource).streamContent());
} catch (NamingException e) {
// Ignore
} catch (Exception e) {
// Unexpected
log(sm.getString("applicationContext.lookup.error", path, getContextPath()), e);
}
}
return (null);
}
use of org.apache.naming.resources.Resource in project tomcat70 by apache.
the class WebappClassLoaderBase method findResourceInternal.
/**
* Find specified resource in local repositories.
*
* @return the loaded resource, or null if the resource isn't found
*/
protected ResourceEntry findResourceInternal(final String name, final String path, final boolean manifestRequired) {
if (!started) {
log.info(sm.getString("webappClassLoader.stopped", name));
return null;
}
if ((name == null) || (path == null))
return null;
JarEntry jarEntry = null;
// Need to skip the leading / to find resources in JARs
String jarEntryPath = path.substring(1);
ResourceEntry entry = resourceEntries.get(path);
if (entry != null) {
if (manifestRequired && entry.manifest == MANIFEST_UNKNOWN) {
// manifest is required, the cache entry needs to be updated.
synchronized (jarFiles) {
if (openJARs()) {
for (int i = 0; i < jarFiles.length; i++) {
jarEntry = jarFiles[i].getJarEntry(jarEntryPath);
if (jarEntry != null) {
try {
entry.manifest = jarFiles[i].getManifest();
} catch (IOException ioe) {
// Ignore
}
break;
}
}
}
}
}
return entry;
}
int contentLength = -1;
InputStream binaryStream = null;
boolean isClassResource = path.endsWith(CLASS_FILE_SUFFIX);
boolean isCacheable = isClassResource;
if (!isCacheable) {
isCacheable = path.startsWith(SERVICES_PREFIX);
}
int jarFilesLength = jarFiles.length;
int repositoriesLength = repositories.length;
int i;
Resource resource = null;
boolean fileNeedConvert = false;
for (i = 0; (entry == null) && (i < repositoriesLength); i++) {
try {
String fullPath = repositories[i] + path;
Object lookupResult = resources.lookup(fullPath);
if (lookupResult instanceof Resource) {
resource = (Resource) lookupResult;
}
// Note : Not getting an exception here means the resource was
// found
ResourceAttributes attributes = (ResourceAttributes) resources.getAttributes(fullPath);
contentLength = (int) attributes.getContentLength();
String canonicalPath = attributes.getCanonicalPath();
if (canonicalPath != null) {
// we create the ResourceEntry based on the information returned
// by the DirContext rather than just using the path to the
// repository. This allows to have smart DirContext implementations
// that "virtualize" the docbase (e.g. Eclipse WTP)
entry = findResourceInternal(new File(canonicalPath), "");
} else {
// probably a resource not in the filesystem (e.g. in a
// packaged war)
entry = findResourceInternal(files[i], path);
}
entry.lastModified = attributes.getLastModified();
if (resource != null) {
try {
binaryStream = resource.streamContent();
} catch (IOException e) {
return null;
}
if (needConvert) {
if (path.endsWith(".properties")) {
fileNeedConvert = true;
}
}
// Note: Only syncing on a 'constant' object is needed
synchronized (allPermission) {
int j;
long[] result2 = new long[lastModifiedDates.length + 1];
for (j = 0; j < lastModifiedDates.length; j++) {
result2[j] = lastModifiedDates[j];
}
result2[lastModifiedDates.length] = entry.lastModified;
lastModifiedDates = result2;
String[] result = new String[paths.length + 1];
for (j = 0; j < paths.length; j++) {
result[j] = paths[j];
}
result[paths.length] = fullPath;
paths = result;
}
}
} catch (NamingException e) {
// Ignore
}
}
if ((entry == null) && (notFoundResources.containsKey(name)))
return null;
synchronized (jarFiles) {
try {
if (!openJARs()) {
return null;
}
for (i = 0; (entry == null) && (i < jarFilesLength); i++) {
jarEntry = jarFiles[i].getJarEntry(jarEntryPath);
if (jarEntry != null) {
entry = new ResourceEntry();
try {
entry.codeBase = getURI(jarRealFiles[i]);
entry.source = UriUtil.buildJarUrl(entry.codeBase.toString(), jarEntryPath);
entry.lastModified = jarRealFiles[i].lastModified();
} catch (MalformedURLException e) {
return null;
}
contentLength = (int) jarEntry.getSize();
try {
if (manifestRequired) {
entry.manifest = jarFiles[i].getManifest();
} else {
entry.manifest = MANIFEST_UNKNOWN;
}
binaryStream = jarFiles[i].getInputStream(jarEntry);
} catch (IOException e) {
return null;
}
// Extract resources contained in JAR to the workdir
if (antiJARLocking && !(path.endsWith(CLASS_FILE_SUFFIX))) {
byte[] buf = new byte[1024];
File resourceFile = new File(loaderDir, jarEntry.getName());
if (!resourceFile.exists()) {
Enumeration<JarEntry> entries = jarFiles[i].entries();
while (entries.hasMoreElements()) {
JarEntry jarEntry2 = entries.nextElement();
if (!(jarEntry2.isDirectory()) && (!jarEntry2.getName().endsWith(CLASS_FILE_SUFFIX))) {
resourceFile = new File(loaderDir, jarEntry2.getName());
try {
if (!resourceFile.getCanonicalPath().startsWith(canonicalLoaderDir)) {
throw new IllegalArgumentException(sm.getString("webappClassLoader.illegalJarPath", jarEntry2.getName()));
}
} catch (IOException ioe) {
throw new IllegalArgumentException(sm.getString("webappClassLoader.validationErrorJarPath", jarEntry2.getName()), ioe);
}
File parentFile = resourceFile.getParentFile();
if (!parentFile.mkdirs() && !parentFile.exists()) {
// Ignore the error (like the IOExceptions below)
}
FileOutputStream os = null;
InputStream is = null;
try {
is = jarFiles[i].getInputStream(jarEntry2);
os = new FileOutputStream(resourceFile);
while (true) {
int n = is.read(buf);
if (n <= 0) {
break;
}
os.write(buf, 0, n);
}
resourceFile.setLastModified(jarEntry2.getTime());
} catch (IOException e) {
// Ignore
} finally {
try {
if (is != null) {
is.close();
}
} catch (IOException e) {
// Ignore
}
try {
if (os != null) {
os.close();
}
} catch (IOException e) {
// Ignore
}
}
}
}
}
}
}
}
if (entry == null) {
synchronized (notFoundResources) {
notFoundResources.put(name, name);
}
return null;
}
/* Only cache the binary content if there is some content
* available one of the following is true:
* a) It is a class file since the binary content is only cached
* until the class has been loaded
* or
* b) The file needs conversion to address encoding issues (see
* below)
* or
* c) The resource is a service provider configuration file located
* under META=INF/services
*
* In all other cases do not cache the content to prevent
* excessive memory usage if large resources are present (see
* https://bz.apache.org/bugzilla/show_bug.cgi?id=53081).
*/
if (binaryStream != null && (isCacheable || fileNeedConvert)) {
byte[] binaryContent = new byte[contentLength];
int pos = 0;
try {
while (true) {
int n = binaryStream.read(binaryContent, pos, binaryContent.length - pos);
if (n <= 0)
break;
pos += n;
}
} catch (IOException e) {
log.error(sm.getString("webappClassLoader.readError", name), e);
return null;
}
if (fileNeedConvert) {
// Workaround for certain files on platforms that use
// EBCDIC encoding, when they are read through FileInputStream.
// See commit message of rev.303915 for details
// http://svn.apache.org/viewvc?view=revision&revision=303915
String str = new String(binaryContent, 0, pos);
try {
binaryContent = str.getBytes(CHARSET_UTF8);
} catch (Exception e) {
return null;
}
}
entry.binaryContent = binaryContent;
// associated input stream has been fully read
if (jarEntry != null) {
entry.certificates = jarEntry.getCertificates();
}
}
} finally {
if (binaryStream != null) {
try {
binaryStream.close();
} catch (IOException e) {
/* Ignore */
}
}
}
}
// Add the entry in the local resource repository
synchronized (resourceEntries) {
// Ensures that all the threads which may be in a race to load
// a particular class all end up with the same ResourceEntry
// instance
ResourceEntry entry2 = resourceEntries.get(path);
if (entry2 == null) {
resourceEntries.put(path, entry);
} else {
entry = entry2;
}
}
return entry;
}
Aggregations