Example usage for org.apache.commons.httpclient HttpStatus SC_FORBIDDEN

List of usage examples for org.apache.commons.httpclient HttpStatus SC_FORBIDDEN

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpStatus SC_FORBIDDEN.

Prototype

int SC_FORBIDDEN

To view the source code for org.apache.commons.httpclient HttpStatus SC_FORBIDDEN.

Click Source Link

Document

<tt>403 Forbidden</tt> (HTTP/1.0 - RFC 1945)

Usage

From source file:es.carebear.rightmanagement.client.group.AddUserToGroup.java

public void AddUser(String executing, String target, String group)
        throws BadRequestException, InternalServerErrorException, IOException, UnknownResponseException {
    PostMethod postMethod = new PostMethod(baseUri + "/client/groups/add/" + target + "/" + group);
    postMethod.addParameter("authName", executing);
    int responseCode = httpClient.executeMethod(postMethod);

    switch (responseCode) {
    case HttpStatus.SC_OK:
        break;//from  www  . ja  v a  2s.com
    case HttpStatus.SC_BAD_REQUEST:
        throw new BadRequestException();
    case HttpStatus.SC_INTERNAL_SERVER_ERROR:
        throw new InternalServerErrorException();
    case HttpStatus.SC_FORBIDDEN:
        throw new ForbiddenException();
    default:
        throw new UnknownResponseException((new Integer(responseCode)).toString());
    }
}

From source file:es.carebear.rightmanagement.client.user.AddAllowedUserId.java

public void AddUser(String authName, String target, String rightMask) throws BadRequestException,
        InternalServerErrorException, IOException, UnknownResponseException, UnauthorizedException {
    PostMethod postMethod = new PostMethod(baseUri + "/client/users/change/allowed");
    postMethod.addParameter("authName", authName);
    postMethod.addParameter("target", target);
    postMethod.addParameter("rightMask", rightMask);
    int responseCode = httpClient.executeMethod(postMethod);

    switch (responseCode) {
    case HttpStatus.SC_OK:
        break;//from www . ja  v  a2  s .c o  m
    case HttpStatus.SC_BAD_REQUEST:
        throw new BadRequestException();
    case HttpStatus.SC_INTERNAL_SERVER_ERROR:
        throw new InternalServerErrorException();
    case HttpStatus.SC_UNAUTHORIZED:
        throw new UnauthorizedException();
    case HttpStatus.SC_FORBIDDEN:
        throw new ForbiddenException();
    default:
        throw new UnknownResponseException((new Integer(responseCode)).toString());
    }
}

From source file:es.carebear.rightmanagement.client.user.ChangeAttributeUser.java

public void ChangeAttribute(String userName, String authName, String[] attribute, String[] value)
        throws BadRequestException, InternalServerErrorException, IOException, UnknownResponseException {
    Gson gson = new Gson();
    String attr = gson.toJson(attribute, attribute.getClass());
    String val = gson.toJson(value, value.getClass());

    PostMethod postMethod = new PostMethod(baseUri + "/client/users/change/" + userName);
    postMethod.addParameter("authName", authName);
    postMethod.addParameter("attribute", attr);
    postMethod.addParameter("value", val);

    int responseCode = httpClient.executeMethod(postMethod);

    switch (responseCode) {
    case HttpStatus.SC_OK:
        break;/*  w  ww. j a  v a2s  .  com*/
    case HttpStatus.SC_BAD_REQUEST:
        throw new BadRequestException();
    case HttpStatus.SC_INTERNAL_SERVER_ERROR:
        throw new InternalServerErrorException();
    case HttpStatus.SC_FORBIDDEN:
        throw new ForbiddenException();
    default:
        throw new UnknownResponseException((new Integer(responseCode)).toString());
    }
}

From source file:edu.emory.cci.aiw.cvrg.eureka.servlet.LoginServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    try {//  w ww.j av  a  2s  .  com
        User user = (User) req.getAttribute("user");
        user.setLastLogin(new Date());
        this.servicesClient.updateUser(user, user.getId());
        resp.sendRedirect(req.getContextPath() + "/index.jsp");
    } catch (ClientException e) {
        Status responseStatus = e.getResponseStatus();
        if (responseStatus == Status.FORBIDDEN) {
            HttpSession session = req.getSession(false);
            if (session != null) {
                session.invalidate();
            }
            resp.sendError(HttpStatus.SC_FORBIDDEN);
        } else {
            throw new ServletException(e);
        }
    }
}

From source file:de.pdark.dsmp.ProxyDownload.java

/**
 * Do the download./* w  w  w.ja  v a 2s.  c om*/
 * 
 * @throws IOException
 * @throws DownloadFailed
 */
public void download() throws IOException, DownloadFailed {
    if (!config.isAllowed(url)) {
        throw new DownloadFailed(
                "HTTP/1.1 " + HttpStatus.SC_FORBIDDEN + " Download denied by rule in DSMP config");
    }

    // If there is a status file in the cache, return it instead of trying it again
    // As usual with caches, this one is a key area which will always cause
    // trouble.
    // TODO There should be a simple way to get rid of the cached statuses
    // TODO Maybe retry a download after a certain time?
    File statusFile = new File(dest.getAbsolutePath() + ".status");
    if (statusFile.exists()) {
        try {
            FileReader r = new FileReader(statusFile);
            char[] buffer = new char[(int) statusFile.length()];
            int len = r.read(buffer);
            r.close();
            String status = new String(buffer, 0, len);
            throw new DownloadFailed(status);
        } catch (IOException e) {
            log.warn("Error writing 'File not found'-Status to " + statusFile.getAbsolutePath(), e);
        }
    }

    mkdirs();

    HttpClient client = new HttpClient();

    String msg = "";
    if (config.useProxy(url)) {
        Credentials defaultcreds = new UsernamePasswordCredentials(config.getProxyUsername(),
                config.getProxyPassword());
        AuthScope scope = new AuthScope(config.getProxyHost(), config.getProxyPort(), AuthScope.ANY_REALM);
        HostConfiguration hc = new HostConfiguration();
        hc.setProxy(config.getProxyHost(), config.getProxyPort());
        client.setHostConfiguration(hc);
        client.getState().setProxyCredentials(scope, defaultcreds);
        msg = "via proxy ";
    }
    log.info("Downloading " + msg + "to " + dest.getAbsolutePath());

    GetMethod get = new GetMethod(url.toString());
    get.setFollowRedirects(true);
    try {
        int status = client.executeMethod(get);

        log.info("Download status: " + status);
        if (0 == 1 && log.isDebugEnabled()) {
            Header[] header = get.getResponseHeaders();
            for (Header aHeader : header)
                log.debug(aHeader.toString().trim());
        }

        log.info("Content: " + valueOf(get.getResponseHeader("Content-Length")) + " bytes; "
                + valueOf(get.getResponseHeader("Content-Type")));

        if (status != HttpStatus.SC_OK) {
            // Remember "File not found"
            if (status == HttpStatus.SC_NOT_FOUND) {
                try {
                    FileWriter w = new FileWriter(statusFile);
                    w.write(get.getStatusLine().toString());
                    w.close();
                } catch (IOException e) {
                    log.warn("Error writing 'File not found'-Status to " + statusFile.getAbsolutePath(), e);
                }
            }
            throw new DownloadFailed(get);
        }

        File dl = new File(dest.getAbsolutePath() + ".new");
        OutputStream out = new BufferedOutputStream(new FileOutputStream(dl));
        IOUtils.copy(get.getResponseBodyAsStream(), out);
        out.close();

        File bak = new File(dest.getAbsolutePath() + ".bak");
        if (bak.exists())
            bak.delete();
        if (dest.exists())
            dest.renameTo(bak);
        dl.renameTo(dest);
    } finally {
        get.releaseConnection();
    }
}

From source file:com.owncloud.android.lib.resources.files.ToggleEncryptionOperation.java

/**
 * @param client Client object/*w w w. j  av a  2 s  . com*/
 */
@Override
protected RemoteOperationResult run(OwnCloudClient client) {
    RemoteOperationResult result;
    HttpMethodBase method = null;

    ReadRemoteFolderOperation remoteFolderOperation = new ReadRemoteFolderOperation(remotePath);
    RemoteOperationResult remoteFolderOperationResult = remoteFolderOperation.execute(client);

    // Abort if not empty
    // Result has always the folder and maybe children, so size == 1 is ok
    if (remoteFolderOperationResult.isSuccess() && remoteFolderOperationResult.getData().size() > 1) {
        return new RemoteOperationResult(false, "Non empty", HttpStatus.SC_FORBIDDEN);
    }

    try {
        String url = client.getBaseUri() + ENCRYPTED_URL + localId;
        if (encryption) {
            method = new PutMethod(url);
        } else {
            method = new DeleteMethod(url);
        }

        // remote request
        method.addRequestHeader(OCS_API_HEADER, OCS_API_HEADER_VALUE);
        method.addRequestHeader(CONTENT_TYPE, FORM_URLENCODED);

        int status = client.executeMethod(method, SYNC_READ_TIMEOUT, SYNC_CONNECTION_TIMEOUT);

        if (status == HttpStatus.SC_OK) {
            result = new RemoteOperationResult(true, method);
        } else {
            result = new RemoteOperationResult(false, method);
            client.exhaustResponse(method.getResponseBodyAsStream());
        }
    } catch (Exception e) {
        result = new RemoteOperationResult(e);
        Log_OC.e(TAG, "Setting encryption status of " + localId + " failed: " + result.getLogMessage(),
                result.getException());
    } finally {
        if (method != null)
            method.releaseConnection();
    }
    return result;
}

From source file:io.relution.jenkins.awssqs.net.SQSChannelImpl.java

@Override
public List<Message> getMessages() {
    try {/*from   w  w  w . j a v a  2s.c om*/
        this.logRequestCount();

        final ReceiveMessageRequest request = this.factory.createReceiveMessageRequest(this.queue);
        final ReceiveMessageResult result = this.sqs.receiveMessage(request);

        if (result == null) {
            return Collections.emptyList();
        }

        return result.getMessages();

    } catch (final com.amazonaws.services.sqs.model.QueueDoesNotExistException e) {
        Log.warning("Failed to send receive message request for %s, queue does not exist", this.queue);
        throw e;

    } catch (final com.amazonaws.AmazonServiceException e) {
        if (ErrorType.is(e, ErrorCode.INVALID_CLIENT_TOKEN_ID, HttpStatus.SC_FORBIDDEN)) {
            Log.warning("Failed to send receive message request for %s, %s", this.queue, e.getMessage());
            throw e;
        }

        Log.severe(e, "Failed to send receive message request for %s", this.queue);
    }
    return Collections.emptyList();
}

From source file:es.carebear.rightmanagement.client.user.AddAllowedUserId.java

public void AddUser(String authName, String target, String rigthTarget, String rightMask)
        throws BadRequestException, InternalServerErrorException, IOException, UnknownResponseException {
    PostMethod postMethod = new PostMethod(baseUri + "/client/users/change/allowed/" + target);
    postMethod.addParameter("authName", authName);
    postMethod.addParameter("rigthTarget", rigthTarget);
    postMethod.addParameter("rightMask", rightMask);
    int responseCode = httpClient.executeMethod(postMethod);

    switch (responseCode) {
    case HttpStatus.SC_OK:
        break;/* w w  w  . j  a v a2s. c  o  m*/
    case HttpStatus.SC_BAD_REQUEST:
        throw new BadRequestException();
    case HttpStatus.SC_INTERNAL_SERVER_ERROR:
        throw new InternalServerErrorException();
    case HttpStatus.SC_FORBIDDEN:
        throw new ForbiddenException();
    default:
        throw new UnknownResponseException((new Integer(responseCode)).toString());
    }
}

From source file:net.sourceforge.fenixedu.presentationTier.Action.publico.FileDownload.java

@Override
public ActionForward execute(final ActionMapping mapping, final ActionForm actionForm,
        final HttpServletRequest request, final HttpServletResponse response) throws Exception {
    final String oid = request.getParameter("oid");
    final File file = FenixFramework.getDomainObject(oid);
    if (file == null) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        response.getWriter().write(HttpStatus.getStatusText(HttpStatus.SC_BAD_REQUEST));
        response.getWriter().close();/*w  w w  .j  a v  a2 s  . c om*/
    } else {
        final Person person = AccessControl.getPerson();
        if (!file.isPrivate() || file.isPersonAllowedToAccess(person)) {
            response.setContentType(file.getContentType());
            response.addHeader("Content-Disposition", "attachment; filename=" + file.getFilename());
            response.setContentLength(file.getSize().intValue());
            final DataOutputStream dos = new DataOutputStream(response.getOutputStream());
            dos.write(file.getContents());
            dos.close();
        } else if (file.isPrivate() && person == null) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write(HttpStatus.getStatusText(HttpStatus.SC_UNAUTHORIZED));
            response.getWriter().close();
        } else {
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            response.getWriter().write(HttpStatus.getStatusText(HttpStatus.SC_FORBIDDEN));
            response.getWriter().close();
        }
    }
    return null;
}

From source file:com.sap.netweaver.porta.core.nw7.FileUploaderImpl.java

public String[] upload(File[] archives) throws CoreException {
    // check if there are any credentials already set
    if (client == null) {
        // trigger the mechanism for requesting user for credentials
        throw new NotAuthorizedException(FAULT_UNAUTHORIZED.getFaultReason());
    }/*from ww  w  .j  a v  a 2s.  co  m*/

    PostMethod method = null;
    try {
        Part[] parts = new Part[archives.length];
        for (int i = 0; i < archives.length; i++) {
            parts[i] = new FilePart(archives[i].getName(), archives[i]);
        }

        method = new PostMethod(url);
        method.setDoAuthentication(true);
        method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams()));

        int statusCode = client.executeMethod(method);
        if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
            throw new NotAuthorizedException(FAULT_INVALID_CREDENTIALS.getFaultReason());
        } else if (statusCode == HttpStatus.SC_FORBIDDEN) {
            throw new NotAuthorizedException(FAULT_PERMISSION_DENIED.getFaultReason());
        } else if (statusCode == HttpStatus.SC_NOT_FOUND) {
            throw new NoWSGateException(null, url);
        } else if (statusCode != HttpStatus.SC_OK) {
            throw new CoreException(method.getStatusText());
        }

        InputStream responseStream = method.getResponseBodyAsStream();
        BufferedReader responseReader = new BufferedReader(new InputStreamReader(responseStream));
        String line;
        List<String> paths = new ArrayList<String>();
        while ((line = responseReader.readLine()) != null) {
            paths.add(line);
        }
        responseReader.close();
        responseStream.close();

        return paths.toArray(new String[] {});
    } catch (HttpException e) {
        throw new CoreException(e);
    } catch (IOException e) {
        throw new CoreException(e);
    } finally {
        if (method != null) {
            method.releaseConnection();
        }
    }
}