Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
 
 package org.apache.marmotta.platform.core.services.content;
 
 
 import java.io.*;
 import java.net.URI;
 import java.util.UUID;
 
 import static org.apache.marmotta.commons.sesame.repository.ExceptionUtils.handleRepositoryException;

A content writer that writes the content of a resource to the file system. It uses the kiwi:hasContentPath property to determine the destination path of the content to write to.

Author: Sebastian Schaffert

 
 public class FileSystemContentWriter implements ContentWriter {
 
     @Inject
     private Logger log;
 
 
     @Inject
 
     @Inject
     private SesameService sesameService;
 
     private String defaultDir;
 
     public FileSystemContentWriter() {
     }
 
     @PostConstruct
     public void initialise() {
          = .getWorkDir()+.+"resources";
 
         .debug("FileSystem Content Writer started (default file location: {})",);
 
         File dir = new File();
         if(!dir.exists() && !dir.mkdirs()) {
             .warn("could not create default directory for file system storage of content (directory: {})",);
         }
     }

    
Delete the content of the speficied mime type for the specified resource.

Parameters:
resource the resource for which to delete the content
mimetype the mime type of the content to delete (optional)
 
     @Override
     public void deleteContent(Resource resourceString mimetypethrows IOException {
         try {
             RepositoryConnection conn = .getConnection();
             try {
                 conn.begin();
                 MediaContentItem mci = FacadingFactory.createFacading(conn).createFacade(resourceMediaContentItem.class);
 
                 String path = mci.getContentPath();
                 if(path != null) {
                     if(!path.startsWith()) {
                         if(!.getBooleanConfiguration("content.filesystem.secure")) {
                             .warn("accessing file {}, which is outside the default directory; this is a potential security risk; " +
                                     "enable the option content.filesystem.secure in the configuration",path);
                         } else {
                            throw new FileNotFoundException("the file "+path+" is outside the Apache Marmotta default directory location; access denied");
                        }
                    }
                    File file = new File(path);
                    if(file.exists() && file.canWrite()) {
                        .info("deleting file {} for resource {} ..."file.getPath(), resource);
                        file.delete();
                    } else {
                        throw new FileNotFoundException("could not delete file "+path+"; it does not exist or is not writable");
                    }
                } else {
                    throw new FileNotFoundException("could not delete file content for resource "+resource+"; no content path has been specified for the resource");
                }
            } finally {
                conn.commit();
                conn.close();
            }
        } catch (RepositoryException ex) {
            handleRepositoryException(ex,FileSystemContentReader.class);
        }
    }

    
Return the name of the content reader. Used to identify and display the content reader to admin users.

Returns:
    @Override
    public String getName() {
        return "FileSystem Content Writer";
    }

    
Store the content of the specified mime type for the specified resource. Accepts a byte array containing the byte data of the content that is then written to the destination configured for this writer.

Parameters:
resource the resource for which to store the content
mimetype the mime type of the content
data a byte array containing the content of the resource
    @Override
    public void setContentData(Resource resourcebyte[] dataString mimetypethrows IOException {
        setContentStream(resourcenew ByteArrayInputStream(data),mimetype);
    }

    
Store the content of the specified mime type for the specified resource. Accepts an input stream containing the byte data of the content that is read and written to the destination configured for this writer.

This method is preferrable for resources with large amounts of data.

Parameters:
resource the resource for which to return the content
mimetype the mime type to retrieve of the content
in a InputStream containing the content of the resource
    @Override
    public void setContentStream(Resource resourceInputStream inString mimetypethrows IOException {
        try {
            RepositoryConnection conn = .getConnection();
            try {
                conn.begin();
                MediaContentItem mci = FacadingFactory.createFacading(conn).createFacade(resourceMediaContentItem.class);
                String path = mci.getContentPath();
                if(path == null) {
                    if(resource instanceof org.openrdf.model.URI && resource.stringValue().startsWith("file:")) {
                        try {
                            URI uri = new URI(resource.stringValue());
                            path = uri.getPath();
                        } catch(Exception ex) {}
                    } else {
                        // we store all other resources in the default directory; create a random file name and store it in the hasContentLocation
                        // property
                        String extension = null;
                        MimeEntry entry = MimeTable.getDefaultTable().find(mimetype);
                        if(entry != null && entry.getExtensions().length > 0) {
                            extension = entry.getExtensions()[0];
                        }
                        String fileName = UUID.randomUUID().toString();
                        path =  + . +
                                fileName.substring(0,2) + . +
                                fileName.substring(2,4) + . +
                                fileName.substring(4,6) + . +
                                fileName + (extension != null ? extension : "");
                        mci.setContentPath(path);
                    }
                }
                if(path != null) {
                    if(!path.startsWith()) {
                        if(!.getBooleanConfiguration("content.filesystem.secure")) {
                            .warn("accessing file {}, which is outside the default directory; this is a potential security risk; " +
                                    "enable the option content.filesystem.secure in the configuration",path);
                        } else {
                            throw new FileNotFoundException("the file "+path+" is outside the Apache Marmotta default directory location; access denied");
                        }
                    }
                    File file = new File(path);
                    if(!file.exists()) {
                        try {
                            file.getParentFile().mkdirs();
                            file.createNewFile();
                        } catch(IOException ex) {
                            throw new FileNotFoundException("could not create file "+path+"; it is not writable");
                        }
                    }
                    if(file.exists() && file.canWrite()) {
                        .debug("writing file content to file {} for resource {} ..."fileresource);
                        ByteStreams.copy(in, Files.newOutputStreamSupplier(file));
                    } else {
                        throw new FileNotFoundException("could not write to file "+path+"; it does not exist or is not writable");
                    }
                } else {
                    throw new FileNotFoundException("could not write file content for resource "+resource+"; no content path has been specified for the resource");
                }
            } finally {
                conn.commit();
                conn.close();
            }
        } catch (RepositoryException ex) {
            handleRepositoryException(ex,FileSystemContentReader.class);
        }
    }
New to GrepCode? Check out our FAQ X