下面列出了怎么用org.apache.http.auth.InvalidCredentialsException的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Send GET request to an external server
* @param loginUrl external url
* @param classObject response object type
* @param username basic auth credential user
* @param password basic auth credential password
* @return response
* @throws Exception error during send request to external location
*/
public Object sendGETRequest(String loginUrl, Class<?> classObject, String username, String password) throws Exception {
if (localJerseyClient == null) {
if (sslConfigurer.isKeyStoreSpecified()) {
sslConfigurer.ensureStorePasswords();
}
localJerseyClient = ThreadLocal.withInitial(() -> sslConfigurer.isKeyStoreSpecified() ?
new JerseyClientBuilder().sslContext(sslConfigurer.getSSLContext()).build() :
JerseyClientBuilder.createClient());
}
String url = authPropsConfig.getExternalAuthHostUrl() + loginUrl;
JerseyClient client = localJerseyClient.get();
HttpAuthenticationFeature authFeature = HttpAuthenticationFeature.basicBuilder()
.credentials(username, password)
.build();
client.register(authFeature);
WebTarget target = client.target(url);
logger.debug("URL: " + url);
Invocation.Builder invocationBuilder = target.request();
try {
Response response = invocationBuilder.get();
if (response.getStatus() != Response.Status.OK.getStatusCode()
&& response.getStatus() != Response.Status.FOUND.getStatusCode()) {
throw new InvalidCredentialsException(String.format("External auth failed with status code: %d, response: %s",
response.getStatus(), response.readEntity(String.class)));
}
return response.readEntity(classObject);
} catch (Exception e) {
throw new Exception(e.getCause());
} finally {
localJerseyClient.remove();
}
}
private synchronized void serveRunStart(HttpServletRequest request,
HttpServletResponse response, String path) throws IOException, CoreException, InvalidCredentialsException {
JSONObject input = parseInput(request);
verifyPassword(input);
IContext context = Core.createSystemContext();
if (!detectedUnitTests) {
TestManager.instance().findAllTests(context);
detectedUnitTests = true;
}
if (testSuiteRunner != null && !testSuiteRunner.isFinished()) {
throw new IllegalArgumentException("Cannot start a test run while another test run is still running");
}
LOG.info("[remote api] starting new test run");
testSuiteRunner = new TestSuiteRunner();
Thread t = new Thread() {
@Override
public void run() {
testSuiteRunner.run();
}
};
t.start();
response.setStatus(HttpServletResponse.SC_NO_CONTENT);
}
private void verifyPassword(JSONObject input) throws InvalidCredentialsException {
if (!input.has(PARAM_PASSWORD)) {
LOG.warn("[remote api] Missing password");
throw new IllegalArgumentException("No '" + PARAM_PASSWORD + "' attribute found in the JSON body. Please provide a password");
}
if (!password.equals(input.getString(PARAM_PASSWORD))) {
LOG.warn("[remote api] Invalid password");
throw new InvalidCredentialsException();
}
}
@Override
public Header authenticate(
final Credentials credentials,
final HttpRequest request,
final HttpContext context ) throws AuthenticationException {
if (request == null) {
throw new IllegalArgumentException("HTTP request may not be null");
}
switch (state) {
case UNINITIATED:
throw new AuthenticationException(getSchemeName() + " authentication has not been initiated");
case FAILED:
throw new AuthenticationException(getSchemeName() + " authentication has failed");
case CHALLENGE_RECEIVED:
try {
token = generateToken(token);
state = State.TOKEN_GENERATED;
} catch (GSSException gsse) {
state = State.FAILED;
if (gsse.getMajor() == GSSException.DEFECTIVE_CREDENTIAL
|| gsse.getMajor() == GSSException.CREDENTIALS_EXPIRED)
throw new InvalidCredentialsException(gsse.getMessage(), gsse);
if (gsse.getMajor() == GSSException.NO_CRED)
throw new InvalidCredentialsException(gsse.getMessage(), gsse);
if (gsse.getMajor() == GSSException.DEFECTIVE_TOKEN
|| gsse.getMajor() == GSSException.DUPLICATE_TOKEN
|| gsse.getMajor() == GSSException.OLD_TOKEN)
throw new AuthenticationException(gsse.getMessage(), gsse);
// other error
throw new AuthenticationException(gsse.getMessage());
}
// continue to next case block
case TOKEN_GENERATED:
String tokenstr = new String(base64codec.encode(token));
if (log.isDebugEnabled()) {
log.debug("Sending response '" + tokenstr + "' back to the auth server");
}
return new BasicHeader("Authorization", "Negotiate " + tokenstr);
default:
throw new IllegalStateException("Illegal state: " + state);
}
}
public ElastiCenterClient(String address, String key) throws InvalidCredentialsException, InvalidParameterException, SSLHandshakeException, ServiceUnavailableException {
elastiCenterAddress = address;
apiKey = key;
initialize();
}
public Object executeCommand(String command, MultivaluedMap<String, String> params, Object responeObj) throws Throwable {
if (!initialized) {
throw new IllegalStateException("Error : ElastiCenterClient is not initialized.");
}
if (command == null || command.trim().isEmpty()) {
throw new InvalidParameterException("No command to execute.");
}
try {
ClientConfig config = new DefaultClientConfig();
Client client = Client.create(config);
WebResource webResource = client.resource(UriBuilder.fromUri(restprotocol + elastiCenterAddress + restpath).build());
MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl();
queryParams.add(queryparamapikey, apiKey);
queryParams.add(queryparamresponse, responseType);
queryParams.add(queryparamcommand, command);
if (null != params) {
for (String key : params.keySet()) {
queryParams.add(key, params.getFirst(key));
}
}
if (debug) {
System.out.println("Command Sent " + command + " : " + queryParams);
}
ClientResponse response = webResource.queryParams(queryParams).accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);
if (response.getStatus() >= 300) {
if (debug)
System.out.println("ElastiCenter returned error code : " + response.getStatus());
if (401 == response.getStatus()) {
throw new InvalidCredentialsException("Please specify a valid API Key.");
} else if (431 == response.getStatus()) {
throw new InvalidParameterException(response.getHeaders().getFirst("X-Description"));
} else if (432 == response.getStatus()) {
throw new InvalidParameterException(command + " does not exist on the ElastiCenter server. Please specify a valid command or contact your ElastiCenter Administrator.");
} else {
throw new ServiceUnavailableException("Internal Error. Please contact your ElastiCenter Administrator.");
}
} else if (null != responeObj) {
String jsonResponse = response.getEntity(String.class);
if (debug) {
System.out.println("Command Response : " + jsonResponse);
}
Gson gson = new Gson();
return gson.fromJson(jsonResponse, responeObj.getClass());
} else {
return "Success";
}
} catch (Throwable t) {
throw t;
}
}