Search in sources :

Example 11 with BadRequestException

use of io.milton.http.exceptions.BadRequestException in project lobcder by skoulouzis.

the class WebDataResource method checkRedirect.

@Override
public String checkRedirect(Request request) throws NotAuthorizedException, BadRequestException {
    switch(request.getMethod()) {
        case PUT:
        case POST:
            if (!redirectPosts) {
                return null;
            }
            String redirect = null;
            try {
                if (!canRedirect(request)) {
                    return null;
                }
                Map<Long, Pair<WebDataFileResource, Long>> resources = createResouses(request);
                // lockResources(resources);
                Map<String, Pair<Long, Collection<Long>>> storageMap = getStorageMap(resources);
                StringBuilder sb = new StringBuilder();
                Set<String> keys = storageMap.keySet();
                for (String k : keys) {
                    sb.append("file_name=").append(k).append("/");
                    Pair pair = storageMap.get(k);
                    Long fileUid = (Long) pair.getLeft();
                    sb.append("file_uid=").append(fileUid).append("/");
                    Long pdriGroupUid = resources.get(fileUid).getRight();
                    sb.append("pdrigroup_uid=").append(pdriGroupUid).append("/");
                    Collection<Long> ssids = (Collection<Long>) pair.getRight();
                    for (Long ssid : ssids) {
                        sb.append("ss_id=").append(ssid).append("/");
                    }
                    sb.append("&");
                }
                sb.deleteCharAt(sb.length() - 1);
                String folder = request.getAbsolutePath();
                if (!folder.endsWith("/")) {
                    folder += "/";
                }
                redirect = "http://localhost:8080/lobcder-worker" + folder + "?" + sb.toString();
            } catch (Exception ex) {
                Logger.getLogger(WebDataResource.class.getName()).log(Level.SEVERE, null, ex);
            }
            return redirect;
        default:
            return null;
    }
// return null;
}
Also used : URISyntaxException(java.net.URISyntaxException) BadRequestException(io.milton.http.exceptions.BadRequestException) PreConditionFailedException(io.milton.http.exceptions.PreConditionFailedException) IOException(java.io.IOException) NotAuthorizedException(io.milton.http.exceptions.NotAuthorizedException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) LockedException(io.milton.http.exceptions.LockedException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) MutablePair(org.apache.commons.lang3.tuple.MutablePair) Pair(org.apache.commons.lang3.tuple.Pair)

Example 12 with BadRequestException

use of io.milton.http.exceptions.BadRequestException in project lobcder by skoulouzis.

the class PutHandler method processReplace.

/**
 * "If an existing resource is modified, either the 200 (OK) or 204 (No
 * Content) response codes SHOULD be sent to indicate successful completion
 * of the request."
 *
 * @param request
 * @param response
 * @param replacee
 */
private void processReplace(HttpManager manager, Request request, Response response, ReplaceableResource replacee) throws BadRequestException, NotAuthorizedException, ConflictException, NotFoundException {
    if (!handlerHelper.checkAuthorisation(manager, replacee, request)) {
        responseHandler.respondUnauthorised(replacee, response, request);
        return;
    }
    try {
        Range range = putHelper.parseContentRange(replacee, request);
        if (range != null) {
            log.debug("partial put: " + range);
            if (replacee instanceof PartialllyUpdateableResource) {
                log.debug("doing partial put on a PartialllyUpdateableResource");
                PartialllyUpdateableResource partialllyUpdateableResource = (PartialllyUpdateableResource) replacee;
                partialllyUpdateableResource.replacePartialContent(range, request.getInputStream());
            } else if (replacee instanceof GetableResource) {
                log.debug("doing partial put on a GetableResource");
                File tempFile = File.createTempFile("milton-partial", null);
                RandomAccessFile randomAccessFile = null;
                // The new length of the resource
                long length;
                try {
                    randomAccessFile = new RandomAccessFile(tempFile, "rw");
                    RandomFileOutputStream tempOut = new RandomFileOutputStream(tempFile);
                    GetableResource gr = (GetableResource) replacee;
                    // Update the content with the supplied partial content, and get the result as an inputstream
                    gr.sendContent(tempOut, null, null, null);
                    // Calculate new length, if the partial put is extending it
                    length = randomAccessFile.length();
                    if (range.getFinish() + 1 > length) {
                        length = range.getFinish() + 1;
                    }
                    randomAccessFile.setLength(length);
                    randomAccessFile.seek(range.getStart());
                    int numBytesRead;
                    byte[] copyBuffer = new byte[1024];
                    InputStream newContent = request.getInputStream();
                    while ((numBytesRead = newContent.read(copyBuffer)) != -1) {
                        randomAccessFile.write(copyBuffer, 0, numBytesRead);
                    }
                } finally {
                    FileUtils.close(randomAccessFile);
                }
                InputStream updatedContent = new FileInputStream(tempFile);
                BufferedInputStream bufin = new BufferedInputStream(updatedContent);
                // Now, finally, we can just do a normal update
                replacee.replaceContent(bufin, length);
            } else {
                throw new BadRequestException(replacee, "Cant apply partial update. Resource does not support PartialllyUpdateableResource or GetableResource");
            }
        } else {
            // Not a partial update, but resource implements Replaceable, so give it the new data
            Long l = request.getContentLengthHeader();
            replacee.replaceContent(request.getInputStream(), l);
        }
    } catch (IOException ex) {
        log.warn("IOException reading input stream. Probably interrupted upload: " + ex.getMessage());
        return;
    }
    // Respond with a 204
    responseHandler.respondNoContent(replacee, response, request);
    log.debug("process: finished");
}
Also used : RandomFileOutputStream(io.milton.common.RandomFileOutputStream) RandomAccessFile(java.io.RandomAccessFile) BufferedInputStream(java.io.BufferedInputStream) BufferedInputStream(java.io.BufferedInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) GetableResource(io.milton.resource.GetableResource) BadRequestException(io.milton.http.exceptions.BadRequestException) IOException(java.io.IOException) Range(io.milton.http.Range) RandomAccessFile(java.io.RandomAccessFile) File(java.io.File) FileInputStream(java.io.FileInputStream)

Example 13 with BadRequestException

use of io.milton.http.exceptions.BadRequestException in project lobcder by skoulouzis.

the class UsersAnnotationHandler method findUser.

public AnnoPrincipalResource findUser(AnnoCollectionResource root, String name) {
    try {
        // a @Authenticate annotation on their ChildOf or ChildrenOf methods
        for (CommonResource col : root.getChildren()) {
            if (col instanceof AnnoCollectionResource) {
                AnnoCollectionResource acr = (AnnoCollectionResource) col;
                List<ControllerMethod> availMethods = getMethods(acr.getSource().getClass());
                if (!availMethods.isEmpty()) {
                    Resource r = acr.child(name);
                    if (r instanceof AnnoPrincipalResource) {
                        AnnoPrincipalResource apr = (AnnoPrincipalResource) r;
                        return apr;
                    }
                }
            }
        }
    } catch (NotAuthorizedException e) {
        throw new RuntimeException(e);
    } catch (BadRequestException e) {
        throw new RuntimeException(e);
    }
    return null;
}
Also used : Resource(io.milton.resource.Resource) BadRequestException(io.milton.http.exceptions.BadRequestException) NotAuthorizedException(io.milton.http.exceptions.NotAuthorizedException)

Example 14 with BadRequestException

use of io.milton.http.exceptions.BadRequestException in project lobcder by skoulouzis.

the class FckQuickUploaderResource method processFileUpload.

private void processFileUpload(FileItem f, Map<String, String> params) throws BadRequestException, NotAuthorizedException {
    CollectionResource target = null;
    if (wrappedResource == null) {
        throw new BadRequestException(this, "collection not found");
    }
    target = (CollectionResource) wrappedResource.child("uploads");
    if (target == null) {
        try {
            if (wrappedResource instanceof MakeCollectionableResource) {
                MakeCollectionableResource mk = (MakeCollectionableResource) wrappedResource;
                target = mk.createCollection("uploads");
            } else {
                throw new BadRequestException(target, "Cant create subfolder");
            }
        } catch (ConflictException ex) {
            throw new RuntimeException(ex);
        } catch (NotAuthorizedException ex) {
            throw new RuntimeException(ex);
        } catch (BadRequestException ex) {
            throw new RuntimeException(ex);
        }
    }
    String name = FileUtils.sanitiseName(f.getName());
    log.debug("processFileUpload: " + name);
    boolean isFirst = true;
    String newName = null;
    while (target.child(name) != null) {
        name = FileUtils.incrementFileName(name, isFirst);
        newName = name;
        isFirst = false;
    }
    long size = f.getSize();
    try {
        if (target instanceof PutableResource) {
            PutableResource putable = (PutableResource) target;
            Resource newRes = putable.createNew(name, f.getInputStream(), size, null);
            if (newRes != null) {
                log.trace("created: " + newRes.getName() + " of type: " + newRes.getClass());
            } else {
                log.trace("createNew returned null");
            }
        } else {
            throw new BadRequestException(target, "Does not implement PutableResource");
        }
    } catch (ConflictException ex) {
        throw new RuntimeException(ex);
    } catch (NotAuthorizedException ex) {
        throw new RuntimeException(ex);
    } catch (BadRequestException ex) {
        throw new RuntimeException(ex);
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }
    try {
        if (newName != null) {
            // we renamed the file
            uploadResponseOk(name);
        } else {
            uploadResponseOk();
        }
    } catch (Throwable ex) {
        log.error("Exception saving new file", ex);
        uploadResponseFailed(ex.getMessage());
    }
}
Also used : CollectionResource(io.milton.resource.CollectionResource) ConflictException(io.milton.http.exceptions.ConflictException) PutableResource(io.milton.resource.PutableResource) MakeCollectionableResource(io.milton.resource.MakeCollectionableResource) Resource(io.milton.resource.Resource) CollectionResource(io.milton.resource.CollectionResource) NotAuthorizedException(io.milton.http.exceptions.NotAuthorizedException) IOException(java.io.IOException) BadRequestException(io.milton.http.exceptions.BadRequestException) MakeCollectionableResource(io.milton.resource.MakeCollectionableResource) PutableResource(io.milton.resource.PutableResource)

Example 15 with BadRequestException

use of io.milton.http.exceptions.BadRequestException in project lobcder by skoulouzis.

the class CompressingResponseHandler method respondContent.

@Override
public void respondContent(Resource resource, Response response, Request request, Map<String, String> params) throws NotAuthorizedException, BadRequestException, NotFoundException {
    if (resource instanceof GetableResource) {
        GetableResource r = (GetableResource) resource;
        String acceptableContentTypes = request.getAcceptHeader();
        String contentType = r.getContentType(acceptableContentTypes);
        // Experimental support for already compressed content...
        String acceptableEncodings = request.getAcceptEncodingHeader();
        if (r instanceof CompressedResource) {
            CompressedResource compressedResource = (CompressedResource) r;
            String acceptableEncoding = compressedResource.getSupportedEncoding(acceptableEncodings);
            if (acceptableEncoding != null) {
                response.setContentTypeHeader(contentType);
                cacheControlHelper.setCacheControl(r, response, request.getAuthorization());
                Long contentLength = compressedResource.getCompressedContentLength(acceptableEncoding);
                response.setContentLengthHeader(contentLength);
                response.setContentEncodingHeader(Response.ContentEncoding.GZIP);
                response.setVaryHeader("Accept-Encoding");
                response.setEntity(new CompressedResourceEntity(compressedResource, params, contentType, acceptableEncoding));
                return;
            }
        }
        if (canCompress(r, contentType, acceptableEncodings)) {
            log.trace("respondContent: compressable");
            // get the zipped content before sending so we can determine its
            // compressed size
            BufferingOutputStream tempOut = new BufferingOutputStream(maxMemorySize);
            try {
                OutputStream gzipOut = new GZIPOutputStream(tempOut);
                r.sendContent(gzipOut, null, params, contentType);
                gzipOut.flush();
                gzipOut.close();
                tempOut.flush();
            } catch (NotFoundException e) {
                throw e;
            } catch (Exception ex) {
                tempOut.deleteTempFileIfExists();
                throw new RuntimeException(ex);
            } finally {
                FileUtils.close(tempOut);
            }
            log.trace("respondContent-compressed: " + resource.getClass());
            setRespondContentCommonHeaders(response, resource, Response.Status.SC_OK, request.getAuthorization());
            response.setContentEncodingHeader(Response.ContentEncoding.GZIP);
            response.setVaryHeader("Accept-Encoding");
            Long contentLength = tempOut.getSize();
            if (contentLength != null) {
                response.setContentLengthHeader(contentLength);
            }
            response.setContentTypeHeader(contentType);
            cacheControlHelper.setCacheControl(r, response, request.getAuthorization());
            response.setEntity(new InputStreamEntity(tempOut.getInputStream()));
        } else {
            log.trace("respondContent: not compressable");
            // We really should set this header, but it causes IE to not cache files (eg images)
            // response.setVaryHeader( "Accept-Encoding" );
            wrapped.respondContent(resource, response, request, params);
        }
    } else {
        throw new RuntimeException("Cant generate content for non-Getable resource: " + resource.getClass());
    }
}
Also used : CompressedResourceEntity(io.milton.http.entity.CompressedResourceEntity) GZIPOutputStream(java.util.zip.GZIPOutputStream) OutputStream(java.io.OutputStream) BufferingOutputStream(io.milton.common.BufferingOutputStream) GZIPOutputStream(java.util.zip.GZIPOutputStream) BufferingOutputStream(io.milton.common.BufferingOutputStream) GetableResource(io.milton.resource.GetableResource) NotFoundException(io.milton.http.exceptions.NotFoundException) BadRequestException(io.milton.http.exceptions.BadRequestException) NotAuthorizedException(io.milton.http.exceptions.NotAuthorizedException) NotFoundException(io.milton.http.exceptions.NotFoundException) InputStreamEntity(io.milton.http.entity.InputStreamEntity)

Aggregations

BadRequestException (io.milton.http.exceptions.BadRequestException)37 NotAuthorizedException (io.milton.http.exceptions.NotAuthorizedException)25 IOException (java.io.IOException)15 Resource (io.milton.resource.Resource)11 ConflictException (io.milton.http.exceptions.ConflictException)10 SQLException (java.sql.SQLException)10 Connection (java.sql.Connection)9 Path (io.milton.common.Path)6 NotFoundException (io.milton.http.exceptions.NotFoundException)6 Permissions (nl.uva.cs.lobcder.auth.Permissions)6 CollectionResource (io.milton.resource.CollectionResource)5 URISyntaxException (java.net.URISyntaxException)5 LogicalData (nl.uva.cs.lobcder.resources.LogicalData)5 ReplaceableResource (io.milton.resource.ReplaceableResource)4 BufferingOutputStream (io.milton.common.BufferingOutputStream)3 Range (io.milton.http.Range)3 PreConditionFailedException (io.milton.http.exceptions.PreConditionFailedException)3 GetableResource (io.milton.resource.GetableResource)3 PostableResource (io.milton.resource.PostableResource)3 UnsupportedEncodingException (java.io.UnsupportedEncodingException)3