Skip to content

Commit

Permalink
Better handling of error code returned by Crowd.
Browse files Browse the repository at this point in the history
Removed manual handling of compressed responses.
Should fix #29 #31
Bumped to version 3.6.2
  • Loading branch information
flopma committed Dec 12, 2017
1 parent 93b47d7 commit 942e323
Show file tree
Hide file tree
Showing 9 changed files with 113 additions and 103 deletions.
4 changes: 2 additions & 2 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,12 @@
<parent>
<groupId>org.sonatype.nexus.plugins</groupId>
<artifactId>nexus-plugins</artifactId>
<version>3.3.1-01</version>
<version>3.6.2-01</version>
</parent>

<groupId>com.roumanoff.nexus</groupId>
<artifactId>nexus-crowd-plugin</artifactId>
<version>3.3.1</version>
<version>3.6.2</version>
<name>${project.groupId}:${project.artifactId}</name>
<packaging>bundle</packaging>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
package org.sonatype.nexus.plugins.crowd.client.rest;

import java.net.URISyntaxException;
import java.rmi.RemoteException;
import java.util.Set;
import java.util.concurrent.TimeUnit;

Expand Down Expand Up @@ -59,7 +58,7 @@ public CachingRestClient(CrowdPluginConfiguration config) throws URISyntaxExcept

@SuppressWarnings("unchecked")
@Override
public Set<String> getNestedGroups(String username) throws RemoteException {
public Set<String> getNestedGroups(String username) throws RestException {
String key = "nestedgroups" + username;
Set<String> elem = groupsCache.get(key);
if (elem != null) {
Expand All @@ -73,7 +72,7 @@ public Set<String> getNestedGroups(String username) throws RemoteException {
}

@Override
public User getUser(String userid) throws RemoteException {
public User getUser(String userid) throws RestException {
String key = "user" + userid;
User elem = userCache.get(key);
if (elem != null) {
Expand All @@ -88,7 +87,7 @@ public User getUser(String userid) throws RemoteException {

@Override
@SuppressWarnings("unchecked")
public Set<Role> getAllGroups() throws RemoteException {
public Set<Role> getAllGroups() throws RestException {
String key = "allgroups";
Set<Role> elem = groupsCache.get(key);
if (elem != null) {
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,10 @@
import java.io.IOException;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.rmi.RemoteException;
import java.util.Collections;
import java.util.HashSet;
import java.util.Objects;
Expand Down Expand Up @@ -52,6 +52,7 @@
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonatype.nexus.plugins.crowd.client.rest.jaxb.AuthenticatePost;
Expand Down Expand Up @@ -112,9 +113,6 @@ public class RestClient {
.setDefaultCredentialsProvider(credsProvider)
.setDefaultRequestConfig(reqConfig);

// handling of compressed responses
hcBuilder.addInterceptorLast(new CompressedHttpResponseInterceptor());


client = hcBuilder.build();

Expand Down Expand Up @@ -142,14 +140,14 @@ protected void finalize() throws Throwable {


/**
* Authenticates a user with crowd. If authentication failed, raises a <code>RemoteException</code>
* Authenticates a user with crowd. If authentication failed, raises a <code>RestException</code>
*
* @param username
* @param password
* @return session token
* @throws RemoteException
* @throws RestException
*/
public void authenticate(String username, String password) throws RemoteException {
public void authenticate(String username, String password) throws RestException {
HttpClientContext hc = HttpClientContext.create();
HttpPost post = new HttpPost(crowdServer.resolve("authentication?username=" + urlEncode(username)));

Expand All @@ -172,8 +170,16 @@ public void authenticate(String username, String password) throws RemoteExceptio

enablePreemptiveAuth(post, hc);
HttpResponse response = client.execute(post);
if (response.getStatusLine().getStatusCode() != 200) {
handleHTTPError(response);

switch (response.getStatusLine().getStatusCode()) {
case HttpURLConnection.HTTP_OK:
return;

case HttpURLConnection.HTTP_BAD_REQUEST:
throw createRestException(response);

default:
handleError(createRestException(response));
}

} catch (IOException | AuthenticationException ioe) {
Expand All @@ -189,9 +195,9 @@ public void authenticate(String username, String password) throws RemoteExceptio
*
* @param username
* @return a set of roles (as strings)
* @throws RemoteException
* @throws RestException
*/
public Set<String> getNestedGroups(String username) throws RemoteException {
public Set<String> getNestedGroups(String username) throws RestException {
if (LOG.isDebugEnabled()) {
LOG.debug("getNestedGroups({})", username);
}
Expand All @@ -211,9 +217,9 @@ public Set<String> getNestedGroups(String username) throws RemoteException {
* Retrieves cookie configurations
*
* @return a <code>ConfigCookieGetResponse</code>
* @throws RemoteException
* @throws RestException
*/
public ConfigCookieGetResponse getCookieConfig() throws RemoteException {
public ConfigCookieGetResponse getCookieConfig() throws RestException {
HttpClientContext hc = HttpClientContext.create();
HttpGet get = new HttpGet(crowdServer.resolve("config/cookie"));

Expand All @@ -227,7 +233,7 @@ public ConfigCookieGetResponse getCookieConfig() throws RemoteException {
enablePreemptiveAuth(acceptXmlResponse(get), hc);
HttpResponse response = client.execute(get);
if (response.getStatusLine().getStatusCode() != 200) {
handleHTTPError(response);
handleError(createRestException(response));
}
configCookie = unmarshal(response, ConfigCookieGetResponse.class);

Expand All @@ -244,9 +250,9 @@ public ConfigCookieGetResponse getCookieConfig() throws RemoteException {
/**
* @param userid
* @return a <code>org.sonatype.security.usermanagement.User</code> from Crowd by a userid
* @throws RemoteException
* @throws RestException
*/
public User getUser(String userid) throws RemoteException {
public User getUser(String userid) throws RestException {
HttpClientContext hc = HttpClientContext.create();
HttpGet get = new HttpGet(crowdServer.resolve("user?username=" + urlEncode(userid)));

Expand All @@ -259,8 +265,16 @@ public User getUser(String userid) throws RemoteException {
try {
enablePreemptiveAuth(acceptXmlResponse(get), hc);
HttpResponse response = client.execute(get);
if (response.getStatusLine().getStatusCode() != 200) {
handleHTTPError(response);

switch(response.getStatusLine().getStatusCode()) {
case HttpURLConnection.HTTP_OK:
break;

case HttpURLConnection.HTTP_NOT_FOUND:
throw createRestException(response);

default:
handleError(createRestException(response));
}

user = unmarshal(response, UserResponse.class);
Expand All @@ -282,10 +296,10 @@ public User getUser(String userid) throws RemoteException {
* @param email
* @param filterGroups
* @return
* @throws RemoteException
* @throws RestException
* @throws UnsupportedEncodingException
*/
public Set<User> searchUsers(String userId) throws RemoteException {
public Set<User> searchUsers(String userId) throws RestException {
LOG.debug("searchUsers({})", userId);

HttpClientContext hc = HttpClientContext.create();
Expand Down Expand Up @@ -314,7 +328,7 @@ public Set<User> searchUsers(String userId) throws RemoteException {
try {
HttpResponse response = client.execute(get);
if (response.getStatusLine().getStatusCode() != 200) {
handleHTTPError(response);
handleError(createRestException(response));
}
users = unmarshal(response, SearchUserGetResponse.class);
} finally {
Expand Down Expand Up @@ -352,9 +366,9 @@ public Set<User> searchUsers(String userId) throws RemoteException {
/**
*
* @return all the crowd groups
* @throws RemoteException
* @throws RestException
*/
public Set<Role> getAllGroups() throws RemoteException {
public Set<Role> getAllGroups() throws RestException {
if (LOG.isDebugEnabled()) {
LOG.debug("getAllGroups()");
}
Expand Down Expand Up @@ -383,7 +397,7 @@ public Set<Role> getAllGroups() throws RemoteException {



private Set<String> getGroupsFromCrowdLoop(HttpClientContext hc, StringBuilder request, int start, int maxResults) throws RemoteException {
private Set<String> getGroupsFromCrowdLoop(HttpClientContext hc, StringBuilder request, int start, int maxResults) throws RestException {
Set<String> results = new HashSet<>();
try {
int startIndex = start;
Expand All @@ -397,10 +411,20 @@ private Set<String> getGroupsFromCrowdLoop(HttpClientContext hc, StringBuilder r

try {
HttpResponse response = client.execute(get);
if (response.getStatusLine().getStatusCode() != 200) {
handleHTTPError(response);

switch(response.getStatusLine().getStatusCode()) {
case HttpURLConnection.HTTP_OK:
break;

case HttpURLConnection.HTTP_NOT_FOUND:
throw createRestException(response);

default:
handleError(createRestException(response));
}

groups = unmarshal(response, GroupsResponse.class);

} finally {
get.releaseConnection();
}
Expand Down Expand Up @@ -471,13 +495,17 @@ private <T> T unmarshal(HttpResponse response, Class<T> type) throws JAXBExcepti
return um.unmarshal(new StreamSource(response.getEntity().getContent()), type).getValue();
}

private void handleHTTPError(HttpResponse response) throws RemoteException {
private RestException createRestException(HttpResponse response) {
StatusLine statusLine = response.getStatusLine();
int status = statusLine.getStatusCode();
String statusText = statusLine.getReasonPhrase();
String body = null;
if (response.getEntity() != null) {
body = response.getEntity().toString();
try {
body = EntityUtils.toString(response.getEntity(), "UTF-8");
} catch (Exception e) {
LOG.debug("Problem occured while reading a HTTP response", e);
}
}

StringBuilder strBuf = new StringBuilder();
Expand All @@ -487,11 +515,11 @@ private void handleHTTPError(HttpResponse response) throws RemoteException {
strBuf.append("\n").append(body);
}

throw new RemoteException(strBuf.toString());
return new RestException(strBuf.toString());
}

private void handleError(Exception e) throws RemoteException {
private void handleError(Exception e) throws RestException {
LOG.error("Error occured while consuming Crowd REST service", e);
throw new RemoteException(e.getMessage());
throw new RestException(e.getMessage());
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
/*
* This program is licensed to you under the Apache License Version 2.0,
* and you may not use this file except in compliance with the Apache License Version 2.0.
* You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0.
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Apache License Version 2.0 is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
*/
package org.sonatype.nexus.plugins.crowd.client.rest;

public class RestException extends Exception {

public RestException() {
super();
}

public RestException(String message) {
super(message);
}

public RestException(Throwable cause) {
super(cause);
}

public RestException(String message, Throwable cause) {
super(message, cause);
}

public RestException(String message, Throwable cause, boolean enableSuppression,
boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}

}
Loading

0 comments on commit 942e323

Please sign in to comment.