Example usage for java.net HttpURLConnection HTTP_FORBIDDEN

List of usage examples for java.net HttpURLConnection HTTP_FORBIDDEN

Introduction

In this page you can find the example usage for java.net HttpURLConnection HTTP_FORBIDDEN.

Prototype

int HTTP_FORBIDDEN

To view the source code for java.net HttpURLConnection HTTP_FORBIDDEN.

Click Source Link

Document

HTTP Status-Code 403: Forbidden.

Usage

From source file:org.opendaylight.plugin2oc.neutron.SubnetHandler.java

/**
 * Invoked when a subnet creation is requested to check if the specified
 * subnet can be created.//from  w ww  .ja  v a 2s .c om
 *
 * @param subnet
 *            An instance of proposed new Neutron Subnet object.
 *
 * @return A HTTP status code to the creation request.
 **/
@Override
public int canCreateSubnet(NeutronSubnet subnet) {
    VirtualNetwork virtualnetwork = new VirtualNetwork();
    apiConnector = Activator.apiConnector;
    if (subnet == null) {
        LOGGER.error("Neutron Subnet can't be null..");
        return HttpURLConnection.HTTP_BAD_REQUEST;
    }
    if (subnet.getCidr() == null || ("").equals(subnet.getCidr())) {
        LOGGER.info("Subnet Cidr can not be empty or null...");
        return HttpURLConnection.HTTP_BAD_REQUEST;
    }
    boolean isvalidGateway = validGatewayIP(subnet, subnet.getGatewayIP());
    if (!isvalidGateway) {
        LOGGER.error("Incorrect gateway IP....");
        return HttpURLConnection.HTTP_BAD_REQUEST;
    }
    try {
        virtualnetwork = (VirtualNetwork) apiConnector.findById(VirtualNetwork.class, subnet.getNetworkUUID());
    } catch (IOException e) {
        e.printStackTrace();
        LOGGER.error("Exception : " + e);
        return HttpURLConnection.HTTP_INTERNAL_ERROR;
    }
    if (virtualnetwork == null) {
        LOGGER.error("No network exists for the specified UUID...");
        return HttpURLConnection.HTTP_FORBIDDEN;
    } else {
        try {
            boolean ifSubnetExist = isSubnetPresent(subnet, virtualnetwork);
            if (ifSubnetExist) {
                LOGGER.error("The subnet already exists..");
                return HttpURLConnection.HTTP_FORBIDDEN;
            }
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("Exception:  " + e);
            return HttpURLConnection.HTTP_INTERNAL_ERROR;
        }
    }
    return HttpURLConnection.HTTP_OK;
}

From source file:org.apache.sentry.api.service.thrift.TestSentryWebServerWithoutSecurity.java

@Test
public void testTraceIsDisabled() throws Exception {
    final URL url = new URL("http://" + SERVER_HOST + ":" + webServerPort);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("TRACE");
    Assert.assertEquals(HttpURLConnection.HTTP_FORBIDDEN, conn.getResponseCode());
}

From source file:mobi.jenkinsci.ci.client.JenkinsHttpClient.java

public HttpResponse execute(final HttpRequestBase req) throws IOException {
    LOG.debug("Executing '" + req.getMethod() + " " + req.getURI() + "'");

    if (!(httpClient instanceof JenkinsFormAuthHttpClient) && config.getUsername() != null
            && config.getUsername().trim().length() > 0) {
        ensurePreemptiveAuthRequest(req);
    }/*from   w  ww  .  ja  v  a2 s  . c om*/

    HttpResponse response = httpContext == null ? httpClient.execute(req)
            : httpClient.execute(req, httpContext);
    if (response == null) {
        throw new IOException("Cannot contact URL " + req.getURI());
    }

    final int responseStatus = response.getStatusLine().getStatusCode();
    if ((responseStatus == HttpURLConnection.HTTP_UNAUTHORIZED
            || responseStatus == HttpURLConnection.HTTP_FORBIDDEN)) {
        req.releaseConnection();

        httpClient = new JenkinsFormAuthHttpClient(httpClientFactory.getHttpClient(), config.getUrl(),
                config.getUsername(), config.getPassword(),
                req.getFirstHeader(Constants.X_AUTH_OTP_HEADER) != null
                        ? req.getFirstHeader(Constants.X_AUTH_OTP_HEADER).getValue()
                        : null);
        response = httpClient.execute(req);
        httpContext = null;
    }

    return elaborateResponse(response);
}

From source file:com.cloudant.http.interceptors.CookieInterceptor.java

@Override
public HttpConnectionInterceptorContext interceptResponse(HttpConnectionInterceptorContext context) {
    HttpURLConnection connection = context.connection.getConnection();
    try {//  www  . ja  v a 2 s.c om
        boolean renewCookie = false;
        int statusCode = connection.getResponseCode();
        switch (statusCode) {
        case HttpURLConnection.HTTP_FORBIDDEN: //403
            //check if it was an expiry case
            InputStream errorStream = connection.getErrorStream();
            String errorString = new String(IOUtils.toString(errorStream, "UTF-8"));
            try {
                JsonObject errorResponse = new Gson().fromJson(errorString, JsonObject.class);
                String error = errorResponse.getAsJsonPrimitive("error").getAsString();
                String reason = errorResponse.getAsJsonPrimitive("reason").getAsString();
                if (!"credentials_expired".equals(error)) {
                    //wasn't a credentials expired, throw exception
                    throw new HttpConnectionInterceptorException(error, reason);
                } else {
                    // Was expired - set boolean to renew cookie
                    renewCookie = true;
                }
            } catch (JsonParseException e) {
                //wasn't JSON throw an exception
                throw new HttpConnectionInterceptorException(errorString);
            } finally {
                errorStream.close();
            }
            break;
        case HttpURLConnection.HTTP_UNAUTHORIZED: //401
            // We need to get a new cookie
            renewCookie = true;
            break;
        default:
            break;
        }
        if (renewCookie) {
            cookie = getCookie(connection.getURL(), context);
            // Don't resend request, failed to get cookie
            if (cookie != null) {
                context.replayRequest = true;
            } else {
                context.replayRequest = false;
            }
        }
    } catch (IOException e) {
        logger.log(Level.SEVERE, "Failed to get response code from request", e);
    }
    return context;

}

From source file:org.apache.geronimo.testsuite.servlets.ServletsTest.java

/**
 * Test6//from ww  w.  j  av a  2 s .c  o  m
 */
@Test
public void test_SampleServlet4_POST_RoleC_Fail() throws Exception {
    Assert.assertEquals(invoke("/SampleServlet4", "POST", "gracie", "biscuit"),
            HttpURLConnection.HTTP_FORBIDDEN);
}

From source file:de.innovationgate.igutils.pingback.PingBackClient.java

private String determinePingBackURI(String targetURI) throws PingBackException {
    HttpClient client = WGFactory.getHttpClientFactory().createHttpClient();
    GetMethod pingbackTargetGET = new GetMethod(targetURI);
    pingbackTargetGET.setFollowRedirects(false);
    try {/*  w w  w  .ja v  a 2s . co m*/
        int responseCode = client.executeMethod(pingbackTargetGET);
        if (responseCode != HttpURLConnection.HTTP_OK) {
            if (responseCode == HttpURLConnection.HTTP_FORBIDDEN) {
                throw new PingBackException(PingBackException.ERROR_ACCESS_DENIED,
                        "Access denied on target '" + targetURI + "'.");
            } else if (responseCode == HttpURLConnection.HTTP_BAD_GATEWAY) {
                throw new PingBackException(PingBackException.ERROR_UPSTREAM_SERVER_COMMUNICATION_ERROR,
                        "Unable to determine ping back target for post. Get request on '" + targetURI
                                + "' returned '" + responseCode + "'.");
            } else {
                throw new PingBackException(PingBackException.ERROR_TARGET_URI_CANNOT_BE_USED_AS_TARGET,
                        "Unable to determine ping back target for post. Get request on '" + targetURI
                                + "' returned '" + responseCode + "'.");
            }
        }

        Header header = pingbackTargetGET.getResponseHeader("X-Pingback");
        if (header != null && header.getValues().length > 0) {
            // retrieve ping back url from header
            HeaderElement headerElement = header.getValues()[0];
            return headerElement.getName();
        } else {
            // retrieve ping back url from link tag

            // check for textual content
            checkTextualContentType(pingbackTargetGET);

            // retrieve input reader an try to find link tag
            InputStream sourceIn = pingbackTargetGET.getResponseBodyAsStream();
            String searchTerm = "<link rel=\"pingback\" href=\"";
            if (sourceIn == null) {
                throw new PingBackException(PingBackException.ERROR_TARGET_URI_CANNOT_BE_USED_AS_TARGET,
                        "TargetURL '" + targetURI + "' cannot be parsed for link tag.");
            } else {
                BufferedReader reader = new BufferedReader(new InputStreamReader(
                        pingbackTargetGET.getResponseBodyAsStream(), pingbackTargetGET.getResponseCharSet()));
                String line = reader.readLine();
                while (line != null) {
                    String orgLine = line;
                    line = line.toLowerCase();
                    int start = line.indexOf(searchTerm);
                    if (start != -1) {
                        if (start + searchTerm.length() <= line.length()) {
                            start = start + searchTerm.length();
                            int end = line.indexOf("\"", start);
                            if (end != -1) {
                                String href = orgLine.substring(start, end);
                                href = href.replaceAll("&amp;", "&");
                                href = href.replaceAll("&lt;", "<");
                                href = href.replaceAll("&gt;", ">");
                                href = href.replaceAll("&quot;", "\"");
                                return href;
                            } else {
                                throw new PingBackException(
                                        PingBackException.ERROR_TARGET_URI_CANNOT_BE_USED_AS_TARGET,
                                        "TargetURL '" + targetURI + "' returned an unparsable link-tag");
                            }
                        } else {
                            throw new PingBackException(
                                    PingBackException.ERROR_TARGET_URI_CANNOT_BE_USED_AS_TARGET,
                                    "TargetURL '" + targetURI + "' returned an unparsable link-tag");
                        }
                    }
                    // if endof head reached - cancel search
                    if (line.indexOf("</head>") != -1 || line.indexOf("<body>") != -1) {
                        throw new PingBackException(PingBackException.ERROR_TARGET_URI_CANNOT_BE_USED_AS_TARGET,
                                "TargetURL '" + targetURI + "' is not pingback-enabled.");
                    }
                    line = reader.readLine();
                }
                throw new PingBackException(PingBackException.ERROR_TARGET_URI_CANNOT_BE_USED_AS_TARGET,
                        "TargetURL '" + targetURI + "' is not pingback-enabled.");
            }
        }
    } catch (HttpException e) {
        throw new PingBackException(PingBackException.ERROR_GENERIC,
                "Unable to determine ping back target for post.", e);
    } catch (IOException e) {
        throw new PingBackException(PingBackException.ERROR_GENERIC,
                "Unable to determine ping back target for post.", e);
    }
}

From source file:org.esupportail.twitter.services.OAuthTwitterApplicationOnlyService.java

public void afterPropertiesSet() throws Exception {
    HttpURLConnection connection = null;
    String encodedCredentials = encodeKeys(oAuthTwitterConfig.getConsumerKey(),
            oAuthTwitterConfig.getConsumerSecret());

    try {// w w w  . j  a  v a 2  s.co  m
        URL url = new URL(URL_TWITTER_OAUTH2_TOKEN);
        connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Host", "api.twitter.com");
        connection.setRequestProperty("User-Agent", ESUPTWITTER_USERAGENT);
        connection.setRequestProperty("Authorization", "Basic " + encodedCredentials);
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
        connection.setRequestProperty("Content-Length", "29");
        connection.setUseCaches(false);

        writeRequest(connection, "grant_type=client_credentials");
        String jsonResponse = readResponse(connection);
        log.debug("jsonResponse of the bearer oauth request : " + jsonResponse);
        if (connection.getResponseCode() == HttpURLConnection.HTTP_FORBIDDEN) {
            log.error(
                    "HTTP 403 (Forbidden) returned from Twitter API call for bearer token. Check values of Consumer Key and Consumer Secret in tokens.properties");
            throw new RejectedAuthorizationException("",
                    "HTTP 403 (Forbidden) returned attempting to get Twitter API bearer token");
        }

        // Parse the JSON response into a JSON mapped object to fetch fields from.
        JSONObject obj = new JSONObject(jsonResponse);

        if (obj != null) {
            applicationOnlyBearerToken = (String) obj.get("access_token");
        }
    } catch (MalformedURLException e) {
        throw new IOException("Invalid endpoint URL specified.", e);
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
}

From source file:com.redhat.ceylon.cmr.repository.webdav.WebDAVRepository.java

public String getBetterExceptionMessage(IOException x, String root) {
    if (x instanceof SardineException) {
        // hide this from callers because its getMessage() is borked
        SardineException sx = (SardineException) x;
        if (sx.getStatusCode() == HttpURLConnection.HTTP_FORBIDDEN) {
            return "authentication failed on repository " + root;
        }//from  w ww  .j a v  a2  s.  c o m
        return sx.getMessage() + ": " + sx.getResponsePhrase() + " " + sx.getStatusCode();
    }
    if (x instanceof ClientProtocolException) {
        // in case of protocol exception (invalid response) we get this sort of
        // chain set up with a null message, so unwrap it for better messages
        if (x.getCause() != null && x.getCause() instanceof ProtocolException)
            return x.getCause().getMessage();
    }
    return null;
}

From source file:com.aptana.jira.core.JiraManager.java

/**
 * Logs into JIRA with a username and password.
 * /*from   w w  w.j  a  va 2  s .c  o  m*/
 * @param username
 *            the username
 * @param password
 *            the password
 * @throws JiraException
 */
public void login(String username, String password) throws JiraException {
    HttpURLConnection connection = null;
    try {
        connection = createConnection(getUserURL(username), username, password);
        int code = connection.getResponseCode();
        if (code == HttpURLConnection.HTTP_OK) {
            this.user = new JiraUser(username, password);
            saveCredentials();
            return;
        }

        if (code == HttpURLConnection.HTTP_UNAUTHORIZED || code == HttpURLConnection.HTTP_FORBIDDEN) {
            throw new JiraException(Messages.JiraManager_BadCredentialsErrMsg);
        }
        throw new JiraException(Messages.JiraManager_UnknownErrMsg);
    } catch (Exception e) {
        throw new JiraException(e.getMessage(), e);
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
}

From source file:org.apache.geronimo.testsuite.servlets.ServletsTest.java

/**
 * Test8/* w w w .  j  ava2 s.  c om*/
 * URL "/SampleServlet3Dynamic" are set both in web.xml and ServletRegistration.Dynamic
 * IN web.xml,GET access is forbidden by all users.
 * In ServletRegistration.Dynamic, GET access is allowled by RoleC
 * But web.xml content's priority is higher.
 */
@Test
public void test_SampleServlet3Dynamic_GET_RoleC_Fail() throws Exception {
    Assert.assertEquals(invoke("/SampleServlet3Dynamic", "GET", "gracie", "biscuit"),
            HttpURLConnection.HTTP_FORBIDDEN);
}