下面列出了java.net.HttpURLConnection#HTTP_NO_CONTENT 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public Optional<SkinModel> downloadSkin(UUID ownerUUID) {
if (crackedUUID.containsKey(ownerUUID) || ownerUUID == null) {
return Optional.empty();
}
//unsigned is needed in order to receive the signature
String uuidString = UUIDTypeAdapter.toMojangId(ownerUUID);
try {
HttpURLConnection conn = getConnection(String.format(SKIN_URL, uuidString));
if (conn.getResponseCode() == HttpURLConnection.HTTP_NO_CONTENT) {
crackedUUID.put(ownerUUID, new Object());
return Optional.empty();
}
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))
) {
return parseSkinTexture(reader);
}
} catch (IOException ex) {
logger.error("Tried downloading skin data of: {} from Mojang", ownerUUID, ex);
}
return Optional.empty();
}
@Override
public void execute() {
if (help) {
processHelpLogs();
return;
}
Configuration configuration = Utils.getConfiguration(password);
HttpClient httpClient = new HttpClient(configuration);
HttpRequest httpRequest = new HttpRequest(
Constants.QUEUES_URL_PARAM + queueName + Constants.PERMISSIONS_OWNER_URL_PARAM,
getJsonRequestPayload());
// do DELETE
HttpResponse response = httpClient.sendHttpRequest(httpRequest, HTTP_PUT);
// handle response
if (response.getStatusCode() == HttpURLConnection.HTTP_NO_CONTENT) {
Message message = new Message("Queue ownership transferred successfully");
ResponseFormatter.printMessage(message);
} else {
ResponseFormatter.handleErrorResponse(buildResponseMessage(response, BROKER_ERROR_MSG));
}
}
@Override
public void execute() {
if (help) {
processHelpLogs();
return;
}
Configuration configuration = Utils.getConfiguration(password);
HttpClient httpClient = new HttpClient(configuration);
HttpRequest httpRequest = new HttpRequest(
Constants.EXCHANGES_URL_PARAM + exchange + Constants.PERMISSIONS_OWNER_URL_PARAM,
getJsonRequestPayload());
// do DELETE
HttpResponse response = httpClient.sendHttpRequest(httpRequest, HTTP_PUT);
// handle response
if (response.getStatusCode() == HttpURLConnection.HTTP_NO_CONTENT) {
Message message = new Message("Exchage ownership transferred successfully");
ResponseFormatter.printMessage(message);
} else {
ResponseFormatter.handleErrorResponse(buildResponseMessage(response, BROKER_ERROR_MSG));
}
}
private Optional<UUID> getUUID(HttpURLConnection connection, String playerName)
throws IOException, RateLimitException, NotPremiumException {
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
throw new NotPremiumException(playerName);
} else if (responseCode == RateLimitException.RATE_LIMIT_ID) {
throw new RateLimitException(playerName);
}
if (responseCode == HttpURLConnection.HTTP_OK) {
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
return parseUUID(reader);
}
} else {
printErrorStream(connection, responseCode);
}
return Optional.empty();
}
private void deleteNamespace(String location) throws Exception {
// System.out.println("Delete namespace at " + location);
URL url = new URL(location);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("DELETE");
conn.setDoOutput(true);
conn.connect();
int responseCode = conn.getResponseCode();
// HTTP 200 or 204
if (responseCode != HttpURLConnection.HTTP_OK && responseCode != HttpURLConnection.HTTP_NO_CONTENT) {
String response = "location " + location + " responded: " + conn.getResponseMessage() + " (" + responseCode
+ ")";
fail(response);
}
}
static int convertErrorCodeFromNendVideoToAdMob(int errorCode) {
switch (errorCode) {
case HttpURLConnection.HTTP_NO_CONTENT:
return AdRequest.ERROR_CODE_NO_FILL;
case HttpURLConnection.HTTP_BAD_REQUEST:
return AdRequest.ERROR_CODE_INVALID_REQUEST;
case NEND_SDK_NETWORK_ERROR_CODE:
return AdRequest.ERROR_CODE_NETWORK_ERROR;
case HttpURLConnection.HTTP_INTERNAL_ERROR:
default:
return AdRequest.ERROR_CODE_INTERNAL_ERROR;
}
}
/**
* {@inheritDoc}
*/
@Override
public Object decode(final Response response, final Type type) throws IOException {
if (
response.status() == HttpURLConnection.HTTP_NO_CONTENT
|| response.body() == null
|| (response.body().length() != null && response.body().length() == 0)
) {
return null;
}
try (final Reader reader = response.body().asReader()) {
return this.mapper.readValue(reader, this.mapper.constructType(type));
} catch (final JsonMappingException jme) {
// The case where for whatever reason (most likely bad design) where the server returned OK and
// trying to de-serialize the content had no content (e.g. the return status should have been no-content)
if (response.status() == HttpURLConnection.HTTP_OK
&& jme.getMessage().startsWith(NO_CONTENT_MESSAGE)) {
return null;
}
throw jme;
} catch (final RuntimeJsonMappingException e) {
if (e.getCause() != null && e.getCause() instanceof IOException) {
throw IOException.class.cast(e.getCause());
}
throw e;
}
}
/**
* Remove the tags from the given resource.
*
* @param tagRemoveRequestDto remove tag request dto
*/
@RequestMapping(
method = RequestMethod.DELETE,
consumes = MediaType.APPLICATION_JSON_VALUE
)
@ResponseStatus(HttpStatus.NO_CONTENT)
@ApiOperation(
value = "Remove the tags from the given resource",
notes = "Remove the tags from the given resource"
)
@ApiResponses(
{
@ApiResponse(
code = HttpURLConnection.HTTP_NO_CONTENT,
message = "The tags were successfully deleted from the table"
),
@ApiResponse(
code = HttpURLConnection.HTTP_NOT_FOUND,
message = "The requested catalog or database or table cannot be located"
)
}
)
public void removeTags(
@ApiParam(value = "Request containing the set of tags and qualifiedName", required = true)
@RequestBody final TagRemoveRequestDto tagRemoveRequestDto
) {
this.requestWrapper.processRequest(
tagRemoveRequestDto.getName(),
"TagV1Resource.removeTableTags",
() -> {
this.removeResourceTags(tagRemoveRequestDto);
return null;
}
);
}
private void putFile(String location, String file) throws Exception {
System.out.println("Put file to " + location);
URL url = new URL(location);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("PUT");
conn.setDoOutput(true);
RDFFormat dataFormat = Rio.getParserFormatForFileName(file).orElse(RDFFormat.RDFXML);
conn.setRequestProperty("Content-Type", dataFormat.getDefaultMIMEType());
try (InputStream dataStream = ProtocolTest.class.getResourceAsStream(file)) {
OutputStream connOut = conn.getOutputStream();
try {
IOUtil.transfer(dataStream, connOut);
} finally {
connOut.close();
}
}
conn.connect();
int responseCode = conn.getResponseCode();
// HTTP 200 or 204
if (responseCode != HttpURLConnection.HTTP_OK && responseCode != HttpURLConnection.HTTP_NO_CONTENT) {
String response = "location " + location + " responded: " + conn.getResponseMessage() + " (" + responseCode
+ ")";
fail(response);
}
}
/**
* Sends an HTTP request to the monitoring service to report performance
* measures of a bounce proxy instance.
*
* @throws IOException
*/
private void sendPerformanceReportAsHttpRequest() throws IOException {
final String url = bounceProxyControllerUrl.buildReportPerformanceUrl();
logger.debug("Using monitoring service URL: {}", url);
Map<String, Integer> performanceMap = bounceProxyPerformanceMonitor.getAsKeyValuePairs();
String serializedMessage = objectMapper.writeValueAsString(performanceMap);
HttpPost postReportPerformance = new HttpPost(url.trim());
// using http apache constants here because JOYNr constants are in
// libjoynr which should not be included here
postReportPerformance.addHeader(HttpHeaders.CONTENT_TYPE, "application/json");
postReportPerformance.setEntity(new StringEntity(serializedMessage, "UTF-8"));
CloseableHttpResponse response = null;
try {
response = httpclient.execute(postReportPerformance);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode != HttpURLConnection.HTTP_NO_CONTENT) {
logger.error("Failed to send performance report: {}", response);
throw new JoynrHttpException(statusCode, "Failed to send performance report.");
}
} finally {
if (response != null) {
response.close();
}
}
}
protected void reportEventAsHttpRequest() throws IOException {
final String url = bounceProxyControllerUrl.buildReportShutdownUrl();
logger.debug("Using monitoring service URL: {}", url);
HttpPut putReportShutdown = new HttpPut(url.trim());
CloseableHttpResponse response = null;
try {
response = httpclient.execute(putReportShutdown);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode != HttpURLConnection.HTTP_NO_CONTENT) {
// unexpected response
logger.error("Failed to send shutdown notification: {}", response);
throw new JoynrHttpException(statusCode,
"Failed to send shutdown notification. Bounce Proxy still registered at Monitoring Service.");
} else {
logger.debug("Successfully sent shutdown notification");
}
} finally {
if (response != null) {
response.close();
}
}
}
/**
* Reports the lifecycle event to the monitoring service as HTTP request.
*
* @throws IOException
* if the connection with the bounce proxy controller could not
* be established
* @throws JoynrHttpException
* if the bounce proxy responded that registering the bounce
* proxy did not succeed
*/
private void reportEventAsHttpRequest() throws IOException {
final String url = bounceProxyControllerUrl.buildReportStartupUrl(controlledBounceProxyUrl);
logger.debug("Using monitoring service URL: {}", url);
HttpPut putReportStartup = new HttpPut(url.trim());
CloseableHttpResponse response = null;
try {
response = httpclient.execute(putReportStartup);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
switch (statusCode) {
case HttpURLConnection.HTTP_NO_CONTENT:
// bounce proxy instance was already known at the bounce proxy
// controller
// nothing else to do
logger.info("Bounce proxy was already registered with the controller");
break;
case HttpURLConnection.HTTP_CREATED:
// bounce proxy instance was registered for the very first time
// TODO maybe read URL
logger.info("Registered bounce proxy with controller");
break;
default:
logger.error("Failed to send startup notification: {}", response);
throw new JoynrHttpException(statusCode,
"Failed to send startup notification. Bounce Proxy won't get any channels assigned.");
}
} finally {
if (response != null) {
response.close();
}
}
}
public <T, P> T getJsonData(final String request, final P payload, final String requestType, final Class<T> clazz) throws UnauthorizedException, GeneralException, NotFoundException {
if (request == null) {
throw new IllegalArgumentException(REQUEST_VALUE_MUST_BE_SPECIFIED);
}
String url = request;
if (!isURLAbsolute(url)) {
url = serviceUrl + url;
}
final APIResponse apiResponse = doRequest(requestType, url, payload);
final String body = apiResponse.getBody();
final int status = apiResponse.getStatus();
if (status == HttpURLConnection.HTTP_OK || status == HttpURLConnection.HTTP_CREATED) {
final ObjectMapper mapper = new ObjectMapper();
// If we as new properties, we don't want the system to fail, we rather want to ignore them
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
// Enable case insensitivity to avoid parsing errors if parameters' case in api response doesn't match sdk's
mapper.enable(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES);
mapper.enable(MapperFeature.ACCEPT_CASE_INSENSITIVE_ENUMS);
try {
return mapper.readValue(body, clazz);
} catch (IOException ioe) {
throw new GeneralException(ioe);
}
} else if (status == HttpURLConnection.HTTP_NO_CONTENT) {
return null; // no content doesn't mean an error
}
handleHttpFailStatuses(status, body);
return null;
}
private void sendMessage(String url, Message msg, MimeBodyPart securedData, String retries) throws Exception {
URL urlObj = new URL(url);
InternetHeaders ih = getHttpHeaders(msg, securedData);
msg.setAttribute(NetAttribute.MA_DESTINATION_IP, urlObj.getHost());
msg.setAttribute(NetAttribute.MA_DESTINATION_PORT, Integer.toString(urlObj.getPort()));
if (logger.isInfoEnabled()) {
logger.info("Connecting to: " + url + msg.getLogMsgID());
}
Map<String, String> httpOptions = getHttpOptions();
httpOptions.put(HTTPUtil.PARAM_HTTP_USER, msg.getPartnership().getAttribute(HTTPUtil.PARAM_HTTP_USER));
httpOptions.put(HTTPUtil.PARAM_HTTP_PWD, msg.getPartnership().getAttribute(HTTPUtil.PARAM_HTTP_PWD));
long maxSize = msg.getPartnership().getNoChunkedMaxSize();
ResponseWrapper resp = HTTPUtil.execRequest(HTTPUtil.Method.POST, url, ih.getAllHeaders(), null, securedData.getInputStream(), httpOptions, maxSize);
if (logger.isInfoEnabled()) {
logger.info("Message sent and response received in " + resp.getTransferTimeMs() + "ms" + msg.getLogMsgID());
}
// Check the HTTP Response code
int rc = resp.getStatusCode();
if ((rc != HttpURLConnection.HTTP_OK) && (rc != HttpURLConnection.HTTP_CREATED) && (rc != HttpURLConnection.HTTP_ACCEPTED) && (rc != HttpURLConnection.HTTP_PARTIAL) && (rc != HttpURLConnection.HTTP_NO_CONTENT)) {
msg.setLogMsg("Error sending message. URL: " + url + " ::: Response Code: " + rc + " " + resp.getStatusPhrase() + " ::: Response Message: " + resp.getBody().toString());
logger.error(msg);
throw new HttpResponseException(url, rc, resp.getStatusPhrase());
}
// So far so good ...
processResponse(msg, resp);
}
private static boolean checkResponseCode(int code) {
return code == HttpURLConnection.HTTP_NO_CONTENT || code == HttpURLConnection.HTTP_OK;
}
public ByteBuffer run( Retriever retriever ) {
if (retriever == null) {
String msg = Logging.getMessage("nullValue.RetrieverIsNull");
Logging.logger().severe(msg);
throw new IllegalArgumentException(msg);
}
try {
if (!retriever.getState().equals(Retriever.RETRIEVER_STATE_SUCCESSFUL))
return null;
URLRetriever r = (URLRetriever) retriever;
ByteBuffer buffer = r.getBuffer();
if (retriever instanceof HTTPRetriever) {
HTTPRetriever htr = (HTTPRetriever) retriever;
if (htr.getResponseCode() == HttpURLConnection.HTTP_NO_CONTENT) {
// Mark tile as missing to avoid excessive attempts
this.layer.getLevels().markResourceAbsent(this.tile);
return null;
} else if (htr.getResponseCode() != HttpURLConnection.HTTP_OK) {
// Also mark tile as missing, but for an unknown reason.
this.layer.getLevels().markResourceAbsent(this.tile);
return null;
}
}
final File outFile = this.layer.getDataFileStore().newFile(this.tile.getPath());
if (outFile == null)
return null;
if (outFile.exists())
return buffer;
// TODO: Better, more generic and flexible handling of file-format type
if (buffer != null) {
String contentType = r.getContentType();
if (contentType == null) {
// TODO: logger message
return null;
}
if (contentType.contains("xml") || contentType.contains("html") || contentType.contains("text")) {
this.layer.getLevels().markResourceAbsent(this.tile);
StringBuffer sb = new StringBuffer();
while( buffer.hasRemaining() ) {
sb.append((char) buffer.get());
}
// TODO: parse out the message if the content is xml or html.
Logging.logger().severe(sb.toString());
return null;
} else if (contentType.contains("dds")) {
this.layer.saveBuffer(buffer, outFile);
} else if (contentType.contains("zip")) {
// Assume it's zipped DDS, which the retriever would have unzipped into the
// buffer.
this.layer.saveBuffer(buffer, outFile);
}
// else if (outFile.getName().endsWith(".dds"))
// {
// // Convert to DDS and save the result.
// buffer = DDSConverter.convertToDDS(buffer, contentType);
// if (buffer != null)
// this.layer.saveBuffer(buffer, outFile);
// }
else if (contentType.contains("image")) {
BufferedImage image = this.layer.convertBufferToImage(buffer);
if (image != null) {
image = this.layer.modifyImage(image);
if (this.layer.isTileValid(image)) {
if (!this.layer.transformAndSave(image, tile.getMercatorSector(), outFile))
image = null;
} else {
this.layer.getLevels().markResourceAbsent(this.tile);
return null;
}
}
if (image == null) {
// Just save whatever it is to the cache.
this.layer.saveBuffer(buffer, outFile);
}
}
if (buffer != null) {
this.layer.firePropertyChange(AVKey.LAYER, null, this);
}
return buffer;
}
} catch (java.io.IOException e) {
this.layer.getLevels().markResourceAbsent(this.tile);
Logging.logger().log(java.util.logging.Level.SEVERE,
Logging.getMessage("layers.TextureLayer.ExceptionSavingRetrievedTextureFile", tile.getPath()), e);
}
return null;
}
private boolean sendAsyncMDN(MessageMDN mdn, String url, DispositionType disposition, Map<Object, Object> options) throws OpenAS2Exception {
Message msg = mdn.getMessage();
try {
// Create a HTTP connection
if (logger.isDebugEnabled()) {
logger.debug("ASYNC MDN attempting connection to: " + url + mdn.getMessage().getLogMsgID());
}
long maxSize = msg.getPartnership().getNoChunkedMaxSize();
Map<String, String> httpOptions = getHttpOptions();
httpOptions.put(HTTPUtil.PARAM_HTTP_USER, msg.getPartnership().getAttribute(HTTPUtil.PARAM_HTTP_USER));
httpOptions.put(HTTPUtil.PARAM_HTTP_PWD, msg.getPartnership().getAttribute(HTTPUtil.PARAM_HTTP_PWD));
ResponseWrapper resp = HTTPUtil.execRequest(HTTPUtil.Method.POST, url, mdn.getHeaders().getAllHeaders(), null, mdn.getData().getInputStream(), httpOptions, maxSize);
int respCode = resp.getStatusCode();
// Check the HTTP Response code
if ((respCode != HttpURLConnection.HTTP_OK) && (respCode != HttpURLConnection.HTTP_CREATED) && (respCode != HttpURLConnection.HTTP_ACCEPTED) && (respCode != HttpURLConnection.HTTP_PARTIAL) && (respCode != HttpURLConnection.HTTP_NO_CONTENT)) {
if (logger.isErrorEnabled()) {
msg.setLogMsg("Error sending AsyncMDN [" + disposition.toString() + "] HTTP response code: " + respCode);
logger.error(msg);
}
throw new HttpResponseException(url, respCode, resp.getStatusPhrase());
}
if (logger.isInfoEnabled()) {
logger.info("sent AsyncMDN [" + disposition.toString() + "] OK " + msg.getLogMsgID());
}
// log & store mdn into backup folder.
getSession().getProcessor().handle(StorageModule.DO_STOREMDN, msg, null);
// Log significant msg state
msg.setOption("STATE", Message.MSG_STATE_MSG_RXD_MDN_SENT_OK);
msg.trackMsgState(getSession());
} catch (HttpResponseException hre) {
// Resend if the HTTP Response has an error code
logger.warn("HTTP exception sending ASYNC MDN: " + org.openas2.logging.Log.getExceptionMsg(hre) + msg.getLogMsgID(), hre);
hre.terminate();
resend(msg, hre);
// Log significant msg state
msg.setOption("STATE", Message.MSG_STATE_MDN_SENDING_EXCEPTION);
msg.trackMsgState(getSession());
return false;
} catch (IOException ioe) {
logger.warn("IO exception sending ASYNC MDN: " + org.openas2.logging.Log.getExceptionMsg(ioe) + msg.getLogMsgID(), ioe);
// Resend if a network error occurs during transmission
WrappedException wioe = new WrappedException(ioe);
wioe.addSource(OpenAS2Exception.SOURCE_MESSAGE, msg);
wioe.terminate();
resend(msg, wioe);
// Log significant msg state
msg.setOption("STATE", Message.MSG_STATE_MDN_SENDING_EXCEPTION);
msg.trackMsgState(getSession());
return false;
} catch (Exception e) {
logger.warn("Unexpected exception sending ASYNC MDN: " + org.openas2.logging.Log.getExceptionMsg(e) + msg.getLogMsgID(), e);
// Propagate error if it can't be handled by a resend
// log & store mdn into backup folder.
getSession().getProcessor().handle(StorageModule.DO_STOREMDN, msg, null);
// Log significant msg state
msg.setOption("STATE", Message.MSG_STATE_MDN_SENDING_EXCEPTION);
msg.trackMsgState(getSession());
throw new WrappedException(e);
}
return true;
}
@Override
public boolean delete(IRemoteSource source) throws NotConnectedException, PermissionException {
if (log.isDebugEnabled()) {
log.debug("Trying to delete " + source);
}
StringBuffer uriTmpl = (new StringBuffer()).append(restDataspaceUrl).append(source.getDataspace().value());
ResteasyClient client = new ResteasyClientBuilder().providerFactory(providerFactory)
.httpEngine(httpEngine)
.build();
ResteasyWebTarget target = client.target(uriTmpl.toString()).path(source.getPath());
List<String> includes = source.getIncludes();
if (includes != null && !includes.isEmpty()) {
target = target.queryParam("includes", includes.toArray(new Object[includes.size()]));
}
List<String> excludes = source.getExcludes();
if (excludes != null && !excludes.isEmpty()) {
target = target.queryParam("excludes", excludes.toArray(new Object[excludes.size()]));
}
Response response = null;
try {
response = target.request().header("sessionid", sessionId).delete();
boolean noContent = false;
if (response.getStatus() != HttpURLConnection.HTTP_NO_CONTENT) {
if (response.getStatus() == HttpURLConnection.HTTP_UNAUTHORIZED) {
throw new NotConnectedException("User not authenticated or session timeout.");
} else {
throw new RuntimeException("Cannot delete file(s). Status :" + response.getStatusInfo() +
" Entity : " + response.getEntity());
}
} else {
noContent = true;
log.debug("No action performed for deletion since source " + source + " was not found remotely");
}
if (!noContent && log.isDebugEnabled()) {
log.debug("Removal of " + source + " performed with success");
}
return true;
} finally {
if (response != null) {
response.close();
}
}
}
/**
* Checks if a response message contains a body.
*
* @see <a href="https://tools.ietf.org/html/rfc7230#section-3.3">RFC 7230 section 3.3</a>
* @param requestMethod request method
* @param responseCode response status code
* @return whether the response has a body
*/
private static boolean hasResponseBody(int requestMethod, int responseCode) {
return requestMethod != Request.Method.HEAD
&& !(HTTP_CONTINUE <= responseCode && responseCode < HttpURLConnection.HTTP_OK)
&& responseCode != HttpURLConnection.HTTP_NO_CONTENT
&& responseCode != HttpURLConnection.HTTP_NOT_MODIFIED;
}
/**
* Attempts to delete the API app with the given client ID.
*
* @param clientId String The Client ID of the app that should be deleted.
* @return boolean true if the API app was successfully deleted
* @throws HelloSignException thrown if there's a problem processing the HTTP request or the
* JSON response.
*/
public boolean deleteApiApp(String clientId) throws HelloSignException {
String url = BASE_URI + API_APP_URI + "/" + clientId;
return HttpURLConnection.HTTP_NO_CONTENT == httpClient.withAuth(auth).delete(url)
.asHttpCode();
}