List of usage examples for java.net HttpURLConnection HTTP_NOT_FOUND
int HTTP_NOT_FOUND
To view the source code for java.net HttpURLConnection HTTP_NOT_FOUND.
Click Source Link
From source file:org.eclipse.hono.service.registration.BaseRegistrationService.java
/** * {@inheritDoc}/*from w ww. ja v a 2s .co m*/ * <p> * Subclasses may override this method in order to implement a more sophisticated approach for asserting registration status, e.g. * using cached information etc. */ @Override public void assertRegistration(final String tenantId, final String deviceId, final String gatewayId, final Handler<AsyncResult<RegistrationResult>> resultHandler) { Objects.requireNonNull(tenantId); Objects.requireNonNull(deviceId); Objects.requireNonNull(gatewayId); Objects.requireNonNull(resultHandler); final Future<RegistrationResult> deviceInfoTracker = Future.future(); final Future<RegistrationResult> gatewayInfoTracker = Future.future(); getDevice(tenantId, deviceId, deviceInfoTracker.completer()); getDevice(tenantId, gatewayId, gatewayInfoTracker.completer()); CompositeFuture.all(deviceInfoTracker, gatewayInfoTracker).compose(ok -> { final RegistrationResult deviceResult = deviceInfoTracker.result(); final RegistrationResult gatewayResult = gatewayInfoTracker.result(); if (!isDeviceEnabled(deviceResult)) { return Future.succeededFuture(RegistrationResult.from(HttpURLConnection.HTTP_NOT_FOUND)); } else if (!isDeviceEnabled(gatewayResult)) { return Future.succeededFuture(RegistrationResult.from(HttpURLConnection.HTTP_FORBIDDEN)); } else { final JsonObject deviceData = deviceResult.getPayload() .getJsonObject(RegistrationConstants.FIELD_DATA, new JsonObject()); final JsonObject gatewayData = gatewayResult.getPayload() .getJsonObject(RegistrationConstants.FIELD_DATA, new JsonObject()); if (isGatewayAuthorized(gatewayId, gatewayData, deviceId, deviceData)) { return Future.succeededFuture(RegistrationResult.from(HttpURLConnection.HTTP_OK, getAssertionPayload(tenantId, deviceId, deviceData), CacheDirective.maxAgeDirective(assertionFactory.getAssertionLifetime()))); } else { return Future.succeededFuture(RegistrationResult.from(HttpURLConnection.HTTP_FORBIDDEN)); } } }).setHandler(resultHandler); }
From source file:com.neoteric.starter.metrics.report.elastic.ElasticsearchReporter.java
private void checkForIndexTemplate() { try {/* w w w. j a v a 2s . c om*/ HttpURLConnection connection = openConnection("/_template/metrics_template", "HEAD"); connection.disconnect(); boolean isTemplateMissing = connection.getResponseCode() == HttpURLConnection.HTTP_NOT_FOUND; // nothing there, lets create it if (isTemplateMissing) { LOGGER.debug("No metrics template found in elasticsearch. Adding..."); HttpURLConnection putTemplateConnection = openConnection("/_template/metrics_template", "PUT"); JsonGenerator json = new JsonFactory().createGenerator(putTemplateConnection.getOutputStream()); json.writeStartObject(); json.writeStringField("template", index + "*"); json.writeObjectFieldStart("mappings"); json.writeObjectFieldStart("_default_"); json.writeObjectFieldStart("_all"); json.writeBooleanField("enabled", false); json.writeEndObject(); json.writeObjectFieldStart("properties"); json.writeObjectFieldStart("name"); json.writeObjectField("type", "string"); json.writeObjectField("index", "not_analyzed"); json.writeEndObject(); json.writeEndObject(); json.writeEndObject(); json.writeEndObject(); json.writeEndObject(); json.flush(); putTemplateConnection.disconnect(); if (putTemplateConnection.getResponseCode() != HttpStatus.OK.value()) { LOGGER.error( "Error adding metrics template to elasticsearch: {}/{}" + putTemplateConnection.getResponseCode(), putTemplateConnection.getResponseMessage()); } } checkedForIndexTemplate = true; } catch (IOException e) { LOGGER.error("Error when checking/adding metrics template to elasticsearch", e); } }
From source file:fr.mael.jiwigo.dao.impl.ImageDaoImpl.java
public void addSimple(File file, Integer category, String title, Integer level) throws JiwigoException { HttpPost httpMethod = new HttpPost(((SessionManagerImpl) sessionManager).getUrl()); // nameValuePairs.add(new BasicNameValuePair("method", "pwg.images.addSimple")); // for (int i = 0; i < parametres.length; i += 2) { // nameValuePairs.add(new BasicNameValuePair(parametres[i], parametres[i + 1])); // }// www .ja va 2 s . c o m // method.setEntity(new UrlEncodedFormEntity(nameValuePairs)); if (file != null) { MultipartEntity multipartEntity = new MultipartEntity(); // String string = nameValuePairs.toString(); // dirty fix to remove the enclosing entity{} // String substring = string.substring(string.indexOf("{"), // string.lastIndexOf("}") + 1); try { multipartEntity.addPart("method", new StringBody(MethodsEnum.ADD_SIMPLE.getLabel())); multipartEntity.addPart("category", new StringBody(category.toString())); multipartEntity.addPart("name", new StringBody(title)); if (level != null) { multipartEntity.addPart("level", new StringBody(level.toString())); } } catch (UnsupportedEncodingException e) { throw new JiwigoException(e); } // StringBody contentBody = new StringBody(substring, // Charset.forName("UTF-8")); // multipartEntity.addPart("entity", contentBody); FileBody fileBody = new FileBody(file); multipartEntity.addPart("image", fileBody); ((HttpPost) httpMethod).setEntity(multipartEntity); } HttpResponse response; StringBuilder sb = new StringBuilder(); try { response = ((SessionManagerImpl) sessionManager).getClient().execute(httpMethod); int responseStatusCode = response.getStatusLine().getStatusCode(); switch (responseStatusCode) { case HttpURLConnection.HTTP_CREATED: break; case HttpURLConnection.HTTP_OK: break; case HttpURLConnection.HTTP_BAD_REQUEST: throw new JiwigoException("status code was : " + responseStatusCode); case HttpURLConnection.HTTP_FORBIDDEN: throw new JiwigoException("status code was : " + responseStatusCode); case HttpURLConnection.HTTP_NOT_FOUND: throw new JiwigoException("status code was : " + responseStatusCode); default: throw new JiwigoException("status code was : " + responseStatusCode); } HttpEntity resultEntity = response.getEntity(); BufferedHttpEntity responseEntity = new BufferedHttpEntity(resultEntity); BufferedReader reader = new BufferedReader(new InputStreamReader(responseEntity.getContent())); String line; try { while ((line = reader.readLine()) != null) { sb.append(line); sb.append("\n"); } } finally { reader.close(); } } catch (ClientProtocolException e) { throw new JiwigoException(e); } catch (IOException e) { throw new JiwigoException(e); } String stringResult = sb.toString(); }
From source file:com.netflix.genie.server.resources.CommandConfigResource.java
/** * Update the configuration files for a given command. * * @param id The id of the command to update the configuration files for. * Not null/empty/blank.// w w w .j av a2s . c o m * @param configs The configuration files to replace existing configuration * files with. Not null/empty/blank. * @return The new set of command configurations. * @throws GenieException For any error */ @PUT @Path("/{id}/configs") @Consumes(MediaType.APPLICATION_JSON) @ApiOperation(value = "Update configuration files for an command", notes = "Replace the existing configuration files for command with given id.", response = String.class, responseContainer = "List") @ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Command not found"), @ApiResponse(code = HttpURLConnection.HTTP_PRECON_FAILED, message = "Invalid required parameter supplied"), @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Genie Server Error due to Unknown Exception") }) public Set<String> updateConfigsForCommand( @ApiParam(value = "Id of the command to update configurations for.", required = true) @PathParam("id") final String id, @ApiParam(value = "The configuration files to replace existing with.", required = true) final Set<String> configs) throws GenieException { LOG.info("Called with id " + id + " and configs " + configs); return this.commandConfigService.updateConfigsForCommand(id, configs); }
From source file:i5.las2peer.services.gamificationApplicationService.GamificationApplicationService.java
/** * Get an app data with specified ID//w ww. j a va 2s.c o m * @param appId applicationId * @return Application data in JSON */ @GET @Path("/data/{appId}") @Produces(MediaType.APPLICATION_JSON) @ApiOperation(value = "getApplicationDetails", notes = "Get an application data with specific ID") @ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Return application data with specific ID"), @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Method not found"), @ApiResponse(code = HttpURLConnection.HTTP_BAD_REQUEST, message = "App not found"), @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Cannot connect to database"), @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Database Error"), @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Failed to process JSON") }) public HttpResponse getApplicationDetails( @ApiParam(value = "Application ID", required = true) @PathParam("appId") String appId) { // Request log L2pLogger.logEvent(this, Event.SERVICE_CUSTOM_MESSAGE_99, "GET " + "gamification/applications/data/" + appId); JSONObject objResponse = new JSONObject(); Connection conn = null; UserAgent userAgent = (UserAgent) getContext().getMainAgent(); String name = userAgent.getLoginName(); if (name.equals("anonymous")) { return unauthorizedMessage(); } try { conn = dbm.getConnection(); if (!applicationAccess.isAppIdExist(conn, appId)) { objResponse.put("message", "Cannot get Application detail. App not found"); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST); } // Add Member to App ApplicationModel app = applicationAccess.getApplicationWithId(conn, appId); ObjectMapper objectMapper = new ObjectMapper(); //Set pretty printing of json objectMapper.enable(SerializationFeature.INDENT_OUTPUT); String appString = objectMapper.writeValueAsString(app); return new HttpResponse(appString, HttpURLConnection.HTTP_OK); } catch (SQLException e) { e.printStackTrace(); objResponse.put("message", "Cannot get Application detail. Database Error. " + e.getMessage()); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR); } catch (JsonProcessingException e) { e.printStackTrace(); objResponse.put("message", "Cannot get Application detail. Failed to process JSON. " + e.getMessage()); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR); } // always close connections finally { try { conn.close(); } catch (SQLException e) { logger.printStackTrace(e); } } }
From source file:i5.las2peer.services.loadStoreGraphService.LoadStoreGraphService.java
/** * /* www. ja v a 2s.com*/ * Returns the API documentation of all annotated resources for purposes of Swagger documentation. * * @return The resource's documentation * */ @GET @Path("/swagger.json") @Produces(MediaType.APPLICATION_JSON) public HttpResponse getSwaggerJSON() { Swagger swagger = new Reader(new Swagger()).read(this.getClass()); if (swagger == null) { return new HttpResponse("Swagger API declaration not available!", HttpURLConnection.HTTP_NOT_FOUND); } try { return new HttpResponse(Json.mapper().writeValueAsString(swagger), HttpURLConnection.HTTP_OK); } catch (JsonProcessingException e) { e.printStackTrace(); return new HttpResponse(e.getMessage(), HttpURLConnection.HTTP_INTERNAL_ERROR); } }
From source file:org.betaconceptframework.astroboa.resourceapi.resource.DefinitionResource.java
private Response getModelInternal(String callback, boolean prettyPrintEnabled, Output outputEnum) { try {/*w w w.j a v a 2 s . c o m*/ if (outputEnum != Output.XML && outputEnum != Output.JSON) { throw new Exception("All definitions are exported only in XML and JSON format. " + outputEnum + " is not supported"); } String allDefinitions = new ModelSerializer(prettyPrintEnabled, outputEnum == Output.JSON, astroboaClient.getDefinitionService(), astroboaClient.getConnectedRepositoryId()).serialize(); if (StringUtils.isBlank(allDefinitions)) { throw new WebApplicationException(HttpURLConnection.HTTP_NOT_FOUND); } StringBuilder definitionAsXMLOrJSONorXSD = new StringBuilder(); if (StringUtils.isBlank(callback)) { definitionAsXMLOrJSONorXSD.append(allDefinitions); } else { switch (outputEnum) { case XML: { ContentApiUtils.generateXMLP(definitionAsXMLOrJSONorXSD, allDefinitions, callback); break; } case JSON: ContentApiUtils.generateJSONP(definitionAsXMLOrJSONorXSD, allDefinitions, callback); break; } } return ContentApiUtils.createResponse(definitionAsXMLOrJSONorXSD, outputEnum, callback, null); } catch (Exception e) { logger.error("When exporting all Definitions", e); throw new WebApplicationException(HttpURLConnection.HTTP_BAD_REQUEST); } }
From source file:com.netflix.genie.server.services.impl.GenieExecutionServiceImpl.java
/** {@inheritDoc} */ @Override//from w ww . j a va 2s .c o m public JobStatusResponse getJobStatus(String jobId) { logger.info("called for jobId: " + jobId); JobStatusResponse response; JobInfoElement jInfo; try { jInfo = pm.getEntity(jobId, JobInfoElement.class); } catch (Exception e) { logger.error("Failed to get job results from database: ", e); response = new JobStatusResponse( new CloudServiceException(HttpURLConnection.HTTP_INTERNAL_ERROR, e.getMessage())); return response; } if (jInfo == null) { String msg = "Job not found: " + jobId; logger.error(msg); response = new JobStatusResponse(new CloudServiceException(HttpURLConnection.HTTP_NOT_FOUND, msg)); return response; } else { response = new JobStatusResponse(); response.setMessage("Returning status for job: " + jobId); response.setStatus(jInfo.getStatus()); return response; } }
From source file:com.netflix.genie.server.resources.ClusterConfigResource.java
/** * Update the configuration files for a given cluster. * * @param id The id of the cluster to update the configuration files for. * Not null/empty/blank./*from w w w .ja v a 2 s.co m*/ * @param configs The configuration files to replace existing configuration * files with. Not null/empty/blank. * @return The new set of cluster configurations. * @throws GenieException For any error */ @PUT @Path("/{id}/configs") @Consumes(MediaType.APPLICATION_JSON) @ApiOperation(value = "Update configuration files for an cluster", notes = "Replace the existing configuration files for cluster with given id.", response = String.class, responseContainer = "List") @ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Cluster not found"), @ApiResponse(code = HttpURLConnection.HTTP_PRECON_FAILED, message = "Invalid required parameter supplied"), @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Genie Server Error due to Unknown Exception") }) public Set<String> updateConfigsForCluster( @ApiParam(value = "Id of the cluster to update configurations for.", required = true) @PathParam("id") final String id, @ApiParam(value = "The configuration files to replace existing with.", required = true) final Set<String> configs) throws GenieException { LOG.info("Called with id " + id + " and configs " + configs); return this.clusterConfigService.updateConfigsForCluster(id, configs); }
From source file:com.netflix.genie.server.resources.ApplicationConfigResource.java
/** * Update the configuration files for a given application. * * @param id The id of the application to update the configuration files * for. Not null/empty/blank. * @param configs The configuration files to replace existing configuration * files with. Not null/empty/blank. * @return The new set of application configurations. * @throws GenieException For any error// w w w .ja v a2s . co m */ @PUT @Path("/{id}/configs") @Consumes(MediaType.APPLICATION_JSON) @ApiOperation(value = "Update configuration files for an application", notes = "Replace the existing configuration files for application with given id.", response = String.class, responseContainer = "List") @ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Application not found"), @ApiResponse(code = HttpURLConnection.HTTP_PRECON_FAILED, message = "Invalid ID supplied"), @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Genie Server Error due to Unknown Exception") }) public Set<String> updateConfigsForApplication( @ApiParam(value = "Id of the application to update configurations for.", required = true) @PathParam("id") final String id, @ApiParam(value = "The configuration files to replace existing with.", required = true) final Set<String> configs) throws GenieException { LOG.info("Called with id " + id + " and configs " + configs); return this.applicationConfigService.updateConfigsForApplication(id, configs); }