Search in sources :

Example 26 with LogicalData

use of nl.uva.cs.lobcder.resources.LogicalData in project lobcder by skoulouzis.

the class Item method getLogicalData.

/**
 * Gets the resource's properties (length, owner, permitions etc.)
 *
 * @param uid the id of the resource
 * @return the resource's properties
 * @throws FileNotFoundException
 * @throws IOException
 * @throws VlException
 * @throws URISyntaxException
 * @throws MalformedURLException
 * @throws Exception
 */
@Path("query/{uid}")
@GET
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public LogicalDataWrapped getLogicalData(@PathParam("uid") Long uid) throws FileNotFoundException, IOException, VlException, URISyntaxException, MalformedURLException, Exception {
    MyPrincipal mp = (MyPrincipal) request.getAttribute("myprincipal");
    try {
        LogicalData resLD = getCatalogue().getLogicalDataByUid(uid);
        if (resLD == null) {
            throw new WebApplicationException(Response.Status.NOT_FOUND);
        }
        Permissions p = getCatalogue().getPermissions(uid, resLD.getOwner());
        if (!mp.canRead(p)) {
            throw new WebApplicationException(Response.Status.UNAUTHORIZED);
        }
        LogicalDataWrapped res = new LogicalDataWrapped();
        res.setGlobalID(getCatalogue().getGlobalID(uid));
        res.setLogicalData(resLD);
        res.setPermissions(p);
        res.setPath(getCatalogue().getPathforLogicalData(resLD));
        if (!resLD.isFolder()) {
            List<PDRIDescr> pdriDescr = getCatalogue().getPdriDescrByGroupId(resLD.getPdriGroupId());
            if (mp.isAdmin()) {
                for (PDRIDescr pdri : pdriDescr) {
                    if (pdri.getResourceUrl().startsWith("lfc") || pdri.getResourceUrl().startsWith("srm") || pdri.getResourceUrl().startsWith("gftp")) {
                        pdriDescr.remove(pdri);
                        GridHelper.initGridProxy(pdri.getUsername(), pdri.getPassword(), null, false);
                        pdri.setPassword(GridHelper.getProxyAsBase64String());
                        pdriDescr.add(pdri);
                    }
                }
            } else {
                for (PDRIDescr pdri : pdriDescr) {
                    pdriDescr.remove(pdri);
                    pdri.setPassword(null);
                    pdri.setUsername(null);
                    pdri.setKey(null);
                    pdri.setId(null);
                    pdri.setPdriGroupRef(null);
                    pdri.setStorageSiteId(null);
                    pdriDescr.add(pdri);
                }
            }
            res.setPdriList(pdriDescr);
        }
        return res;
    } catch (SQLException ex) {
        Logger.getLogger(Item.class.getName()).log(Level.SEVERE, null, ex);
        throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
    }
}
Also used : LogicalData(nl.uva.cs.lobcder.resources.LogicalData) MyPrincipal(nl.uva.cs.lobcder.auth.MyPrincipal) SQLException(java.sql.SQLException) PDRIDescr(nl.uva.cs.lobcder.resources.PDRIDescr) Permissions(nl.uva.cs.lobcder.auth.Permissions) LogicalDataWrapped(nl.uva.cs.lobcder.rest.wrappers.LogicalDataWrapped) Path(javax.ws.rs.Path)

Example 27 with LogicalData

use of nl.uva.cs.lobcder.resources.LogicalData in project lobcder by skoulouzis.

the class WebDataDirResource method createNew.

@Override
public Resource createNew(String newName, InputStream inputStream, Long length, String contentType) throws IOException, ConflictException, NotAuthorizedException, BadRequestException, InternalError {
    Logger.getLogger(WebDataDirResource.class.getName()).log(Level.FINEST, "createNew. for {0}\n\t newName:\t{1}\n\t length:\t{2}\n\t contentType:\t{3}", new Object[] { getPath(), newName, length, contentType });
    LogicalData fileLogicalData;
    // List<PDRIDescr> pdriDescrList;
    WebDataFileResource resource;
    PDRI pdri;
    double start = System.currentTimeMillis();
    try (Connection connection = getCatalogue().getConnection()) {
        try {
            // Long uid = getCatalogue().getLogicalDataUidByParentRefAndName(getLogicalData().getUid(), newName, connection);
            Path newPath = Path.path(getPath(), newName);
            fileLogicalData = getCatalogue().getLogicalDataByPath(newPath, connection);
            if (contentType == null || contentType.equals("application/octet-stream")) {
                contentType = mimeTypeMap.get(FilenameUtils.getExtension(newName));
            }
            if (fileLogicalData != null) {
                // Resource exists, update
                // throw new ConflictException(this, newName);
                Permissions p = getCatalogue().getPermissions(fileLogicalData.getUid(), fileLogicalData.getOwner(), connection);
                if (!getPrincipal().canWrite(p)) {
                    throw new NotAuthorizedException(this);
                }
                fileLogicalData.setLength(length);
                fileLogicalData.setModifiedDate(System.currentTimeMillis());
                fileLogicalData.setLastAccessDate(fileLogicalData.getModifiedDate());
                if (contentType == null) {
                    contentType = mimeTypeMap.get(FilenameUtils.getExtension(newName));
                }
                fileLogicalData.addContentType(contentType);
                resource = new WebDataFileResource(fileLogicalData, Path.path(getPath(), newName), getCatalogue(), authList);
                // LockToken tocken = resource.getCurrentLock();
                // System.err.println("tokenId: "+tocken.tokenId+" lockedByUser: "+tocken.info.lockedByUser+" timeout: "+tocken.timeout.toString()+" getOtherSeconds: "+tocken.timeout.getOtherSeconds()+" getSeconds: "+tocken.timeout.getSeconds());
                // if (tocken != null) {
                // if (tocken.getFrom().after(new Date(System.currentTimeMillis()))) {
                // throw new ConflictException(resource, "The resource is locked");
                // }
                // }
                // Create new
                pdri = createPDRI(fileLogicalData.getLength(), newName, connection);
                pdri.setLength(length);
                pdri.putData(inputStream);
                fileLogicalData = getCatalogue().updateLogicalDataAndPdri(fileLogicalData, pdri, connection);
                // fileLogicalData = inheritProperties(fileLogicalData, connection);
                connection.commit();
                connection.close();
            // String md5 = pdri.getStringChecksum();
            // if (md5 != null) {
            // fileLogicalData.setChecksum(md5);
            // }
            // return new WebDataFileResource(fileLogicalData, Path.path(getPath(), newName), getCatalogue(), authList);
            } else {
                // Resource does not exists, create a new one
                // new need write prmissions for current collection
                fileLogicalData = new LogicalData();
                fileLogicalData.setName(newName);
                fileLogicalData.setParentRef(getLogicalData().getUid());
                fileLogicalData.setType(Constants.LOGICAL_FILE);
                fileLogicalData.setOwner(getPrincipal().getUserId());
                fileLogicalData.setLength(length);
                fileLogicalData.setCreateDate(System.currentTimeMillis());
                fileLogicalData.setModifiedDate(System.currentTimeMillis());
                fileLogicalData.setLastAccessDate(System.currentTimeMillis());
                fileLogicalData.setTtlSec(getLogicalData().getTtlSec());
                fileLogicalData.addContentType(contentType);
                pdri = createPDRI(length, newName, connection);
                pdri.setLength(length);
                pdri.putData(inputStream);
                // String md5 = pdri.getStringChecksum();
                // if (md5 != null) {
                // fileLogicalData.setChecksum(md5);
                // }
                fileLogicalData = getCatalogue().associateLogicalDataAndPdri(fileLogicalData, pdri, connection);
                getCatalogue().setPermissions(fileLogicalData.getUid(), new Permissions(getPrincipal(), getPermissions()), connection);
                // fileLogicalData = inheritProperties(fileLogicalData, connection);
                getCatalogue().setPreferencesOn(fileLogicalData.getUid(), getLogicalData().getUid(), connection);
                List<String> pref = getLogicalData().getDataLocationPreferences();
                fileLogicalData.setDataLocationPreferences(pref);
                connection.commit();
                connection.close();
                resource = new WebDataFileResource(fileLogicalData, Path.path(getPath(), newName), getCatalogue(), authList);
            // return new WebDataFileResource(fileLogicalData, Path.path(getPath(), newName), getCatalogue(), authList);
            }
        } catch (NoSuchAlgorithmException ex) {
            if (connection != null && !connection.isClosed()) {
                connection.rollback();
                connection.close();
            }
            Logger.getLogger(WebDataDirResource.class.getName()).log(Level.SEVERE, null, ex);
            throw new InternalError(ex.getMessage());
        } catch (SQLException e) {
            Logger.getLogger(WebDataDirResource.class.getName()).log(Level.SEVERE, null, e);
            if (connection != null && !connection.isClosed()) {
                connection.rollback();
                connection.close();
            }
            throw new BadRequestException(this, e.getMessage());
        }
    } catch (SQLException | IOException e1) {
        Logger.getLogger(WebDataDirResource.class.getName()).log(Level.SEVERE, null, e1);
        throw new BadRequestException(this, e1.getMessage());
    // throw new InternalError(e1.getMessage());
    }
    double elapsed = System.currentTimeMillis() - start;
    double speed = ((resource.getLogicalData().getLength() * 8.0) * 1000.0) / (elapsed * 1000.0);
    String msg = null;
    try {
        Stats stats = new Stats();
        stats.setSource(fromAddress);
        stats.setDestination(pdri.getHost());
        stats.setSpeed(speed);
        stats.setSize(resource.getLogicalData().getLength());
        if (!pdri.isCahce()) {
            getCatalogue().setSpeed(stats);
        }
        msg = "Source: " + fromAddress + " Destination: " + new URI(pdri.getURI()).getScheme() + "://" + pdri.getHost() + " Rx_Speed: " + speed + " Kbites/sec Rx_Size: " + (resource.getLogicalData().getLength()) + " bytes Elapsed_Time: " + elapsed + " ms";
    } catch (URISyntaxException | SQLException ex) {
        Logger.getLogger(WebDataDirResource.class.getName()).log(Level.SEVERE, null, ex);
    }
    Logger.getLogger(WebDataDirResource.class.getName()).log(Level.INFO, msg);
    return resource;
}
Also used : Path(io.milton.common.Path) SQLException(java.sql.SQLException) Connection(java.sql.Connection) NotAuthorizedException(io.milton.http.exceptions.NotAuthorizedException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) PDRI(nl.uva.cs.lobcder.resources.PDRI) LogicalData(nl.uva.cs.lobcder.resources.LogicalData) Permissions(nl.uva.cs.lobcder.auth.Permissions) Stats(nl.uva.cs.lobcder.rest.wrappers.Stats) BadRequestException(io.milton.http.exceptions.BadRequestException)

Example 28 with LogicalData

use of nl.uva.cs.lobcder.resources.LogicalData in project lobcder by skoulouzis.

the class WebDataDirResource method moveTo.

@Override
public void moveTo(CollectionResource toCollection, String name) throws ConflictException, NotAuthorizedException, BadRequestException {
    WebDataDirResource toWDDR = (WebDataDirResource) toCollection;
    Logger.getLogger(WebDataDirResource.class.getName()).log(Level.FINEST, "moveTo({0}, ''{1}'') for {2}", new Object[] { toWDDR.getPath(), name, getPath() });
    try (Connection connection = getCatalogue().getConnection()) {
        try {
            Permissions destPerm = getCatalogue().getPermissions(toWDDR.getLogicalData().getUid(), toWDDR.getLogicalData().getOwner(), connection);
            LogicalData parentLD = getCatalogue().getLogicalDataByUid(getLogicalData().getParentRef());
            Permissions parentPerm = getCatalogue().getPermissions(parentLD.getUid(), parentLD.getOwner());
            if (!(getPrincipal().canWrite(destPerm) && getPrincipal().canWrite(parentPerm))) {
                throw new NotAuthorizedException(this);
            }
            getCatalogue().moveEntry(getLogicalData(), toWDDR.getLogicalData(), name, connection);
            connection.commit();
            connection.close();
        } catch (SQLException e) {
            Logger.getLogger(WebDataDirResource.class.getName()).log(Level.SEVERE, null, e);
            if (connection != null && !connection.isClosed()) {
                connection.rollback();
                connection.close();
            }
            throw new BadRequestException(this, e.getMessage());
        }
    } catch (SQLException e1) {
        Logger.getLogger(WebDataDirResource.class.getName()).log(Level.SEVERE, null, e1);
        throw new BadRequestException(this, e1.getMessage());
    }
}
Also used : LogicalData(nl.uva.cs.lobcder.resources.LogicalData) SQLException(java.sql.SQLException) Connection(java.sql.Connection) Permissions(nl.uva.cs.lobcder.auth.Permissions) BadRequestException(io.milton.http.exceptions.BadRequestException) NotAuthorizedException(io.milton.http.exceptions.NotAuthorizedException)

Example 29 with LogicalData

use of nl.uva.cs.lobcder.resources.LogicalData in project lobcder by skoulouzis.

the class WebDataDirResource method sendContent.

@Override
public void sendContent(OutputStream out, Range range, Map<String, String> params, String contentType) throws IOException, NotAuthorizedException, BadRequestException {
    Logger.getLogger(WebDataDirResource.class.getName()).log(Level.FINEST, "sendContent({0}) for {1}", new Object[] { contentType, getPath() });
    try (Connection connection = getCatalogue().getConnection()) {
        try (PrintStream ps = new PrintStream(out)) {
            HtmlCanvas html = new HtmlCanvas();
            html.table(border("1")).tr().th().content("Name").th().content("Size").th().content("Modification Date").th().content("Creation Date").th().content("Owner").th().content("Content Type").th().content("Type").th().content("Is Supervised").th().content("Uid");
            String ref;
            for (LogicalData ld : getCatalogue().getChildrenByParentRef(getLogicalData().getUid(), connection)) {
                if (ld.isFolder()) {
                    ref = "../dav" + getPath() + "/" + ld.getName();
                // if (ld.getUid() != 1) {
                // } else {
                // }
                } else {
                    ref = "../dav" + getPath() + "/" + ld.getName();
                }
                html._tr().tr().td().a(href(ref)).img(src("").alt(ld.getName()))._a()._td().td().content(String.valueOf(ld.getLength())).td().content(new Date(ld.getModifiedDate()).toString()).td().content(new Date(ld.getCreateDate()).toString()).td().content(ld.getOwner()).td().content(ld.getContentTypesAsString()).td().content(ld.getType()).td().content(ld.getSupervised().toString()).td().content(ld.getUid().toString());
            }
            html._tr()._table();
            ps.println(html.toHtml());
            getCatalogue().addViewForRes(getLogicalData().getUid(), connection);
            connection.commit();
            connection.close();
        } catch (Exception e) {
            if (connection != null && !connection.isClosed()) {
                connection.rollback();
                connection.close();
            }
            throw e;
        }
    } catch (Exception e) {
        Logger.getLogger(WebDataDirResource.class.getName()).log(Level.SEVERE, null, e);
        throw new BadRequestException(this);
    }
}
Also used : LogicalData(nl.uva.cs.lobcder.resources.LogicalData) Connection(java.sql.Connection) HtmlCanvas(org.rendersnake.HtmlCanvas) BadRequestException(io.milton.http.exceptions.BadRequestException) ConflictException(io.milton.http.exceptions.ConflictException) URISyntaxException(java.net.URISyntaxException) SQLException(java.sql.SQLException) BadRequestException(io.milton.http.exceptions.BadRequestException) PreConditionFailedException(io.milton.http.exceptions.PreConditionFailedException) NotAuthorizedException(io.milton.http.exceptions.NotAuthorizedException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException)

Example 30 with LogicalData

use of nl.uva.cs.lobcder.resources.LogicalData in project lobcder by skoulouzis.

the class WebDataDirResource method createCollection.

@Override
public CollectionResource createCollection(String newName) throws NotAuthorizedException, ConflictException, BadRequestException {
    Logger.getLogger(WebDataDirResource.class.getName()).log(Level.FINEST, "createCollection {0} in {1}", new Object[] { newName, getPath() });
    try (Connection connection = getCatalogue().getConnection()) {
        try {
            Path newCollectionPath = Path.path(getPath(), newName);
            Long newFolderEntryId = getCatalogue().getLogicalDataUidByParentRefAndName(getLogicalData().getUid(), newName, connection);
            if (newFolderEntryId != null) {
                throw new ConflictException(this, newName);
            } else {
                // collection does not exists, create a new one
                // newCollectionPath, Constants.LOGICAL_FOLDER,
                LogicalData newFolderEntry = new LogicalData();
                newFolderEntry.setType(Constants.LOGICAL_FOLDER);
                newFolderEntry.setParentRef(getLogicalData().getUid());
                newFolderEntry.setName(newName);
                newFolderEntry.setCreateDate(System.currentTimeMillis());
                newFolderEntry.setModifiedDate(System.currentTimeMillis());
                newFolderEntry.setLastAccessDate(System.currentTimeMillis());
                newFolderEntry.setTtlSec(getLogicalData().getTtlSec());
                newFolderEntry.setOwner(getPrincipal().getUserId());
                getCatalogue().setPermissions(getCatalogue().registerDirLogicalData(newFolderEntry, connection).getUid(), new Permissions(getPrincipal(), getPermissions()), connection);
                newFolderEntry = inheritProperties(newFolderEntry, connection);
                connection.commit();
                connection.close();
                WebDataDirResource res = new WebDataDirResource(newFolderEntry, newCollectionPath, getCatalogue(), authList);
                return res;
            }
        } catch (SQLException e) {
            Logger.getLogger(WebDataDirResource.class.getName()).log(Level.SEVERE, null, e);
            if (connection != null && !connection.isClosed()) {
                connection.rollback();
                connection.close();
            }
            throw new BadRequestException(this, e.getMessage());
        }
    } catch (SQLException e1) {
        Logger.getLogger(WebDataDirResource.class.getName()).log(Level.SEVERE, null, e1);
        throw new BadRequestException(this, e1.getMessage());
    }
}
Also used : Path(io.milton.common.Path) LogicalData(nl.uva.cs.lobcder.resources.LogicalData) ConflictException(io.milton.http.exceptions.ConflictException) SQLException(java.sql.SQLException) Connection(java.sql.Connection) Permissions(nl.uva.cs.lobcder.auth.Permissions) BadRequestException(io.milton.http.exceptions.BadRequestException)

Aggregations

LogicalData (nl.uva.cs.lobcder.resources.LogicalData)71 Connection (java.sql.Connection)29 SQLException (java.sql.SQLException)29 Permissions (nl.uva.cs.lobcder.auth.Permissions)29 MyPrincipal (nl.uva.cs.lobcder.auth.MyPrincipal)20 PreparedStatement (java.sql.PreparedStatement)11 ResultSet (java.sql.ResultSet)10 Path (io.milton.common.Path)7 ArrayList (java.util.ArrayList)7 BadRequestException (io.milton.http.exceptions.BadRequestException)6 NotAuthorizedException (io.milton.http.exceptions.NotAuthorizedException)5 PDRIDescr (nl.uva.cs.lobcder.resources.PDRIDescr)5 ConflictException (io.milton.http.exceptions.ConflictException)4 URISyntaxException (java.net.URISyntaxException)4 Stack (java.util.Stack)4 Path (javax.ws.rs.Path)4 LogicalDataWrapped (nl.uva.cs.lobcder.rest.wrappers.LogicalDataWrapped)4 VRL (nl.uva.vlet.vrl.VRL)4 PreConditionFailedException (io.milton.http.exceptions.PreConditionFailedException)3 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)3