下面列出了java.net.HttpURLConnection#HTTP_UNAUTHORIZED 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private ThingUID getThingUID() {
DsAPI digitalSTROMClient = new DsAPIImpl(HOST_ADDRESS, Config.DEFAULT_CONNECTION_TIMEOUT,
Config.DEFAULT_READ_TIMEOUT, true);
String dSID = null;
switch (digitalSTROMClient.checkConnection("123")) {
case HttpURLConnection.HTTP_OK:
case HttpURLConnection.HTTP_UNAUTHORIZED:
case HttpURLConnection.HTTP_FORBIDDEN:
Map<String, String> dsidMap = digitalSTROMClient.getDSID(null);
if (dsidMap != null) {
dSID = dsidMap.get(JSONApiResponseKeysEnum.DSID.getKey());
}
if (StringUtils.isNotBlank(dSID)) {
return new ThingUID(DigitalSTROMBindingConstants.THING_TYPE_DSS_BRIDGE, dSID);
} else {
logger.error("Can't get server dSID to generate ThingUID. Please add the server manually.");
}
}
return null;
}
@POST
@Path("/{id}/processes")
@Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON, MediaType.APPLICATION_FORM_URLENCODED })
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON, MediaType.APPLICATION_FORM_URLENCODED })
@ApiOperation(value = "Add ProcessOption", response = ProcessOptionInputModel.class)
@ApiResponses(value = {
@ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns a ProcessOption was updated", response = ProcessOptionInputModel.class),
@ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized", response = ExceptionModel.class),
@ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found", response = ExceptionModel.class),
@ApiResponse(code = HttpURLConnection.HTTP_FORBIDDEN, message = "Access denied", response = ExceptionModel.class) })
public Response addProcessOption(@Context HttpServletRequest request, @Context HttpHeaders header,
@Context Company company, @Context Locale locale, @Context User user,
@Context ServiceContext serviceContext,
@ApiParam(value = "serviceconfigId for get detail") @PathParam("id") long id,
@ApiParam(value = "input model for ProcessOption") @BeanParam ProcessOptionInputModel input);
@POST
@Path("/{id}/checkstep")
@Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON, MediaType.APPLICATION_FORM_URLENCODED })
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@ApiOperation(value = "Add a Dossier", response = DossierDetailModel.class)
@ApiResponses(value = {
@ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns a Dossier was created", response = DossierDetailModel.class),
@ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized", response = ExceptionModel.class),
@ApiResponse(code = HttpURLConnection.HTTP_FORBIDDEN, message = "Access denied", response = ExceptionModel.class),
@ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal error", response = ExceptionModel.class) })
public Response checkStep(@Context HttpServletRequest request, @Context HttpHeaders header,
@Context Company company, @Context Locale locale, @Context User user,
@Context ServiceContext serviceContext, @PathParam("id") String id);
@GET
@Path("/{id}/reset")
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@ApiOperation(value = "Reset Dossier", response = DossierDetailModel.class)
@ApiResponses(value = {
@ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns a Dossier has been reset", response = DossierDetailModel.class),
@ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized", response = ExceptionModel.class),
@ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found", response = ExceptionModel.class),
@ApiResponse(code = HttpURLConnection.HTTP_FORBIDDEN, message = "Access denied", response = ExceptionModel.class) })
public Response resetDossier(@Context HttpServletRequest request, @Context HttpHeaders header,
@Context Company company, @Context Locale locale, @Context User user,
@Context ServiceContext serviceContext, @PathParam("id") String id);
@DELETE
@Path("/lucene")
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@ApiOperation(value = "Remove a Dossier by its id", response = DossierDetailModel.class)
@ApiResponses(value = {
@ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns a Dossier was removed", response = DossierDetailModel.class),
@ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized", response = ExceptionModel.class),
@ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found", response = ExceptionModel.class),
@ApiResponse(code = HttpURLConnection.HTTP_FORBIDDEN, message = "Access denied", response = ExceptionModel.class) })
public Response removeConflictDossier(@Context HttpServletRequest request, @Context HttpHeaders header,
@Context Company company, @Context Locale locale, @Context User user,
@Context ServiceContext serviceContext);
@DELETE
@Path("/deliverables/lucene/resolveconflict")
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@ApiOperation(value = "Get a Dossier by its id", response = DossierDetailModel.class)
@ApiResponses(value = {
@ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns a Dossier was removed", response = DossierDetailModel.class),
@ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized", response = ExceptionModel.class),
@ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found", response = ExceptionModel.class),
@ApiResponse(code = HttpURLConnection.HTTP_FORBIDDEN, message = "Access denied", response = ExceptionModel.class) })
public Response resolveConflictDeliverables(@Context HttpServletRequest request, @Context HttpHeaders header,
@Context Company company, @Context Locale locale, @Context User user,
@Context ServiceContext serviceContext);
@GET
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@ApiOperation(value = "Get a list of Dossiers", response = DossierResultsModel.class)
@ApiResponses(value = {
@ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns a list of Dossiers have been filtered", response = DossierResultsModel.class),
@ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized", response = ExceptionModel.class),
@ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found", response = ExceptionModel.class),
@ApiResponse(code = HttpURLConnection.HTTP_FORBIDDEN, message = "Access denied", response = ExceptionModel.class) })
public Response getDossiers(@Context HttpServletRequest request, @Context HttpHeaders header,
@Context Company company, @Context Locale locale, @Context User user,
@Context ServiceContext serviceContext, @BeanParam DossierSearchModel query);
private byte[] readToken() throws IOException, AuthenticationException {
int status = conn.getResponseCode();
if (status == HttpURLConnection.HTTP_OK || status == HttpURLConnection.HTTP_UNAUTHORIZED) {
String authHeader = conn.getHeaderField(WWW_AUTHENTICATE);
if (authHeader == null || !authHeader.trim().startsWith(NEGOTIATE)) {
throw new AuthenticationException("Invalid SPNEGO sequence, '" + WWW_AUTHENTICATE +
"' header incorrect: " + authHeader);
}
String negotiation = authHeader.trim().substring((NEGOTIATE + " ").length()).trim();
return Base64.getDecoder().decode(negotiation);
}
throw new AuthenticationException("Invalid SPNEGO sequence, status code: " + status);
}
@DELETE
@Path("/{id}")
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@ApiOperation(value = "Remove a Deliverabletypes by its id", response = DeliverableTypesModel.class)
@ApiResponses(value = {
@ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns a Dossier was removed", response = DeliverableTypesModel.class),
@ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized", response = ExceptionModel.class),
@ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found", response = ExceptionModel.class),
@ApiResponse(code = HttpURLConnection.HTTP_FORBIDDEN, message = "Access denied", response = ExceptionModel.class) })
public Response removeDeliverabletypes(@Context HttpServletRequest request, @Context HttpHeaders header,
@Context Company company, @Context Locale locale, @Context User user,
@Context ServiceContext serviceContext, @PathParam("id") String id);
public static RuntimeException createError(int error, String response, String description)
{
switch (error)
{
// 5xx error codes...
case HttpURLConnection.HTTP_UNAVAILABLE:
return new OsmServiceUnavailableException(error, response, description);
// 4xx error codes...
case HttpURLConnection.HTTP_NOT_FOUND:
case HttpURLConnection.HTTP_GONE:
return new OsmNotFoundException(error, response, description);
case HttpURLConnection.HTTP_FORBIDDEN:
case HttpURLConnection.HTTP_UNAUTHORIZED:
/* 401 unauthorized is returned if the user is not authenticated at all
* 403 forbidden is returned if the user is authenticated, but does not have the
* permission to do the action*/
return new OsmAuthorizationException(error, response, description);
case HttpURLConnection.HTTP_CONFLICT:
return new OsmConflictException(error, response, description);
case HttpURLConnection.HTTP_BAD_REQUEST:
return new OsmBadUserInputException(error, response, description);
default:
return createGenericError(error, response, description);
}
}
@DELETE
@Path("/{id}/processes/{optionId}")
@Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON, MediaType.APPLICATION_FORM_URLENCODED })
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON, MediaType.APPLICATION_FORM_URLENCODED })
@ApiOperation(value = "Add ProcessOption", response = ProcessOptionInputModel.class)
@ApiResponses(value = {
@ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns a ProcessOption was updated", response = ProcessOptionInputModel.class),
@ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized", response = ExceptionModel.class),
@ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found", response = ExceptionModel.class),
@ApiResponse(code = HttpURLConnection.HTTP_FORBIDDEN, message = "Access denied", response = ExceptionModel.class) })
public Response removeProcessOption(@Context HttpServletRequest request, @Context HttpHeaders header,
@Context Company company, @Context Locale locale, @Context User user,
@Context ServiceContext serviceContext,
@ApiParam(value = "serviceconfigId for remove") @PathParam("id") long id,
@ApiParam(value = "processOptionId for remove") @PathParam("optionId") long optionId);
@PUT
@Path("/{id}")
@Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON, MediaType.APPLICATION_FORM_URLENCODED })
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON, MediaType.APPLICATION_FORM_URLENCODED })
@ApiOperation(value = "Update a ServiceConfig by id", response = ServiceConfigInputModel.class)
@ApiResponses(value = {
@ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns a ServiceConfig was updated", response = ServiceConfigInputModel.class),
@ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized", response = ExceptionModel.class),
@ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found", response = ExceptionModel.class),
@ApiResponse(code = HttpURLConnection.HTTP_FORBIDDEN, message = "Access denied", response = ExceptionModel.class) })
public Response updateServiceConfig(@Context HttpServletRequest request, @Context HttpHeaders header,
@Context Company company, @Context Locale locale, @Context User user,
@Context ServiceContext serviceContext,
@ApiParam(value = "serviceconfigId for updating") @PathParam("id") long id,
@ApiParam(value = "body params for post") @BeanParam ServiceConfigInputModel input);
@DELETE
@Path("/{certid}")
@Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON, MediaType.APPLICATION_FORM_URLENCODED })
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@ApiOperation(value = "Delete info deliverable by id")
@ApiResponses(value = {
@ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns"),
@ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized", response = ExceptionModel.class),
@ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not Found", response = ExceptionModel.class),
@ApiResponse(code = HttpURLConnection.HTTP_FORBIDDEN, message = "Access defined", response = ExceptionModel.class) })
public Response removeCertNumbers(@Context HttpServletRequest request, @Context HttpHeaders header,
@Context Company company, @Context Locale locale, @Context User user, @Context ServiceContext serviceContext,
@ApiParam(value = "id of certNumber", required = true) @PathParam("certid") String certId);
@GET
@Path("/{id}/processstep")
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@ApiOperation(value = "restrictDossier")
@ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "certificateNumber"),
@ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized", response = ExceptionModel.class),
@ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found", response = ExceptionModel.class),
@ApiResponse(code = HttpURLConnection.HTTP_FORBIDDEN, message = "Access denied", response = ExceptionModel.class) })
public Response getProcessStepByDossierId(@Context HttpServletRequest request, @Context HttpHeaders header,
@Context Company company, @Context Locale locale, @Context User user,
@Context ServiceContext serviceContext,
@ApiParam(value = "dossier id", required = true) @PathParam("id") String id);
@GET
@Path("/number/{certificateNumber}")
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@ApiOperation(value = "certificateNumber")
@ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "certificateNumber"),
@ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized", response = ExceptionModel.class),
@ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found", response = ExceptionModel.class),
@ApiResponse(code = HttpURLConnection.HTTP_FORBIDDEN, message = "Access denied", response = ExceptionModel.class) })
public Response getDossierByCertificateNumber(@Context HttpServletRequest request, @Context HttpHeaders header,
@Context Company company, @Context Locale locale, @Context User user,
@Context ServiceContext serviceContext,
@ApiParam(value = "certificateNumber", required = true) @PathParam("certificateNumber") String certificateNumber);
private void checkStatusCode(HttpURLConnection conn) throws IOException {
switch (conn.getResponseCode()) {
case HttpURLConnection.HTTP_BAD_REQUEST:
throw new TrelloBadRequestException(IOUtils.toString(conn.getErrorStream()));
case HttpURLConnection.HTTP_UNAUTHORIZED:
throw new NotAuthorizedException();
case HttpURLConnection.HTTP_NOT_FOUND:
throw new NotFoundException("Resource not found: " + conn.getURL());
}
}
private URLConnection openConnection(URL aSource) throws IOException {
// set up the URL connection
URLConnection connection = aSource.openConnection();
// modify the headers
// NB: things like user authentication could go in here too.
if (hasTimestamp) {
connection.setIfModifiedSince(timestamp);
}
// in case the plugin manager is its own project, this can become an authenticator
boolean isSecureProcotol = "https".equalsIgnoreCase(aSource.getProtocol());
boolean isAuthInfoSet = !Strings.isNullOrEmpty(aSource.getUserInfo());
if (isAuthInfoSet) {
if (!isSecureProcotol) {
throw new IOException("Basic auth is only supported for HTTPS!");
}
String basicAuth = Base64.encodeBytes(aSource.getUserInfo().getBytes(StandardCharsets.UTF_8));
connection.setRequestProperty("Authorization", "Basic " + basicAuth);
}
if (connection instanceof HttpURLConnection) {
((HttpURLConnection) connection).setInstanceFollowRedirects(false);
connection.setUseCaches(true);
connection.setConnectTimeout(5000);
}
connection.setRequestProperty("ES-Version", Version.CURRENT.toString());
connection.setRequestProperty("ES-Build-Hash", Build.CURRENT.hashShort());
connection.setRequestProperty("User-Agent", "elasticsearch-plugin-manager");
// connect to the remote site (may take some time)
connection.connect();
// First check on a 301 / 302 (moved) response (HTTP only)
if (connection instanceof HttpURLConnection) {
HttpURLConnection httpConnection = (HttpURLConnection) connection;
int responseCode = httpConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_MOVED_PERM ||
responseCode == HttpURLConnection.HTTP_MOVED_TEMP ||
responseCode == HttpURLConnection.HTTP_SEE_OTHER) {
String newLocation = httpConnection.getHeaderField("Location");
URL newURL = new URL(newLocation);
if (!redirectionAllowed(aSource, newURL)) {
return null;
}
return openConnection(newURL);
}
// next test for a 304 result (HTTP only)
long lastModified = httpConnection.getLastModified();
if (responseCode == HttpURLConnection.HTTP_NOT_MODIFIED
|| (lastModified != 0 && hasTimestamp && timestamp >= lastModified)) {
// not modified so no file download. just return
// instead and trace out something so the user
// doesn't think that the download happened when it
// didn't
return null;
}
// test for 401 result (HTTP only)
if (responseCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
String message = "HTTP Authorization failure";
throw new IOException(message);
}
}
//REVISIT: at this point even non HTTP connections may
//support the if-modified-since behaviour -we just check
//the date of the content and skip the write if it is not
//newer. Some protocols (FTP) don't include dates, of
//course.
return connection;
}
protected void handleHttpRetryException(HttpRetryException e) throws IOException {
String msg = "HTTP response '" + e.responseCode() + ": "
+ getResponseMessage() + "' invoking " + url;
switch (e.responseCode()) {
case HttpURLConnection.HTTP_MOVED_PERM: // 301
case HttpURLConnection.HTTP_MOVED_TEMP: // 302
case HttpURLConnection.HTTP_SEE_OTHER: // 303
case 307:
msg += " that returned location header '" + e.getLocation() + "'";
break;
case HttpURLConnection.HTTP_UNAUTHORIZED: // 401
if (authorizationPolicy == null || authorizationPolicy.getUserName() == null) {
msg += " with NO authorization username configured in conduit " + getConduitName();
} else {
msg += " with authorization username '" + authorizationPolicy.getUserName() + "'";
}
break;
case HttpURLConnection.HTTP_PROXY_AUTH: // 407
if (proxyAuthorizationPolicy == null || proxyAuthorizationPolicy.getUserName() == null) {
msg += " with NO proxy authorization configured in conduit " + getConduitName();
} else {
msg += " with proxy authorization username '"
+ proxyAuthorizationPolicy.getUserName() + "'";
}
if (clientSidePolicy == null || clientSidePolicy.getProxyServer() == null) {
if (usingProxy()) {
msg += " using a proxy even if NONE is configured in CXF conduit "
+ getConduitName()
+ " (maybe one is configured by java.net.ProxySelector)";
} else {
msg += " but NO proxy was used by the connection (none configured in cxf "
+ "conduit and none selected by java.net.ProxySelector)";
}
} else {
msg += " using " + clientSidePolicy.getProxyServerType() + " proxy "
+ clientSidePolicy.getProxyServer() + ":"
+ clientSidePolicy.getProxyServerPort();
}
break;
default:
// No other type of HttpRetryException should be thrown
break;
}
throw new IOException(msg, e);
}
public boolean isUnauthorized() {
return responseCode == HttpURLConnection.HTTP_UNAUTHORIZED;
}
private boolean authFailed(BoxHttpResponse response) {
if (response == null){
return false;
}
return response.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED;
}