List of usage examples for org.springframework.http HttpStatus PRECONDITION_FAILED
HttpStatus PRECONDITION_FAILED
To view the source code for org.springframework.http HttpStatus PRECONDITION_FAILED.
Click Source Link
From source file:cu.uci.coj.restapi.controller.RestExtrasController.java
@ApiOperation(value = "Postear Entrada", notes = "Permite postear una entrada.", response = String.class) @ApiResponses(value = { @ApiResponse(code = 400, message = "incorrect request"), @ApiResponse(code = 401, message = "username token mismatch<br> hash incorrect<br> token expirated<br> username apikey mismatch<br> apikey hash incorrect<br> apikey expirated<br> apikey secret incorrect<br> token or apikey incorrect"), @ApiResponse(code = 412, message = "text must not be empty<br> entry text too long") }) @RequestMapping(value = "/entry", method = RequestMethod.POST, headers = "Accept=application/json", consumes = MediaType.APPLICATION_JSON_VALUE) @ResponseBody/*www. j a v a2s.c om*/ public ResponseEntity<?> addEntry(@ApiParam(value = "JSON para enviar") @RequestBody InputEntryRest bodyjson) { try { int error = ValidateApiAndToken(bodyjson.getApikey(), bodyjson.getToken()); if (error > 0) { return new ResponseEntity<>(TokenUtils.ErrorMessage(error), HttpStatus.UNAUTHORIZED); } Entry entry = new Entry(bodyjson.getEntryText(), Calendar.getInstance().getTime()); if (ValidateEntry(entry) != null) return new ResponseEntity<>("{\"error\":\"" + ValidateEntry(entry) + "\"}", HttpStatus.PRECONDITION_FAILED); preProcessEntry(entry); String username = ExtractUser(bodyjson.getToken()); entryDAO.addEntry(entry, isAdmin(username), username); } catch (Exception e) { return new ResponseEntity<>(TokenUtils.ErrorMessage(8), HttpStatus.BAD_REQUEST); } return new ResponseEntity<>(HttpStatus.OK); }
From source file:cu.uci.coj.restapi.controller.RestUserProfileController.java
@ApiOperation(value = "Modificar Perfil de Usuario", notes = "Modifica el perfil de usuario con los datos enviados.") @ApiResponses(value = {//from w w w . j a v a 2 s . c o m @ApiResponse(code = 401, message = "username token mismatch<br> hash incorrect<br> token expirated<br> username apikey mismatch<br> apikey hash incorrect<br> apikey expirated<br> apikey secret incorrect<br> token or apikey incorrect"), @ApiResponse(code = 400, message = "institution witout country<br> incorrect request"), @ApiResponse(code = 412, message = "Nick must not more than 25 characters<br> Nick must not less than 3 characters<br> The first name is too short<br> The first name is too long<br> The first name contains invalid characters<br> The last name is too long<br> The last name is too short<br> The last name contains invalid characters<br> Required field<br> This e-mail already exists<br> Invalid email."), @ApiResponse(code = 404, message = "bad user<br> bad institution id<br> bad language<br> bad locale<br> bad gender<br> bad country id"), @ApiResponse(code = 500, message = "failed send email"), }) @RequestMapping(value = "/update", method = RequestMethod.PUT, headers = "Accept=application/json", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE) @ResponseBody public ResponseEntity<?> UpdateProfile( @ApiParam(value = "Llave de desarrollador") @RequestParam(value = "apikey") String apikey, @ApiParam(value = "Token de usuario") @RequestParam(value = "token") String token, @ApiParam(value = "Ao de nacimiento") @RequestParam(value = "year", required = false) Integer year, @ApiParam(value = "Mes de nacimiento") @RequestParam(value = "month", required = false) Integer month, @ApiParam(value = "Da de nacimiento") @RequestParam(value = "day", required = false) Integer day, @ApiParam(value = "Apodo") @RequestParam(value = "nick", required = false) String nick, @ApiParam(value = "Nombre") @RequestParam(value = "name", required = false) String name, @ApiParam(value = "Apellido") @RequestParam(value = "lastname", required = false) String lastname, @ApiParam(value = "Correo") @RequestParam(value = "email", required = false) String email, @ApiParam(value = "Identificador del Pas") @RequestParam(value = "country_id", required = false) Integer country_id, @ApiParam(value = "Identificador de la Institucin") @RequestParam(value = "institution_id", required = false) Integer institution_id, @ApiParam(value = "Identificador del lenguaje favorito (Ver filters)") @RequestParam(value = "lid", required = false) Integer lid, @ApiParam(value = "Identificador del idioma favorito (Ver filters)") @RequestParam(value = "locale", required = false) Integer locale, @ApiParam(value = "Sexo: (1)Hombre (2) Mujer", allowableValues = "1,2") @RequestParam(value = "gender", required = false) Integer gender) { try { int error = ValidateApiAndToken(apikey, token); if (error > 0) { return new ResponseEntity<>(TokenUtils.ErrorMessage(error), HttpStatus.UNAUTHORIZED); } String username = null; username = ExtractUser(token); User user = userDAO.loadAllUserData(username); if (year != null) user.setYear(year); if (month != null) user.setMonth(month); if (day != null) user.setDay(day); user.setUsername(username); if (nick != null) user.setNick(nick); if (name != null) user.setName(name); if (lastname != null) user.setLastname(lastname); if (email != null) user.setEmail(email); if (country_id != null) user.setCountry_id(country_id); if (institution_id != null) user.setInstitution_id(institution_id); if (lid != null) user.setLid(lid); if (locale != null) user.setLocale(locale); if (gender != null) user.setGender(gender); user.setUid(userDAO.integer("select.uid.by.username", username)); user.setDob(new Date(user.getYear() - 1900, user.getMonth() - 1, user.getDay())); boolean is_team = !userDAO.bool("is.user", user.getUsername()); if (is_team) return new ResponseEntity<>(ErrorUtils.BAD_USER, HttpStatus.NOT_FOUND); user.setTeam(false); String errors = ValidateUser(user); if (!errors.equals("0")) return new ResponseEntity<>(errors, HttpStatus.PRECONDITION_FAILED); if (country_id != null && !ValidateCountry(country_id)) return new ResponseEntity<>(ErrorUtils.BAD_COUNTRY_ID, HttpStatus.NOT_FOUND); if (country_id != null && institution_id != null && !ValidateInstitutionID(country_id, institution_id)) return new ResponseEntity<>(ErrorUtils.BAD_INSTITUTION_ID, HttpStatus.NOT_FOUND); if (country_id == null && institution_id != null) return new ResponseEntity<>(ErrorUtils.INSTITUTION_WITHOUT_COUNTRY, HttpStatus.BAD_REQUEST); if (lid != null && !ValidateLanguage(lid)) return new ResponseEntity<>(ErrorUtils.BAD_LANGUAGE, HttpStatus.NOT_FOUND); if (locale != null && !ValidateLocale(locale)) return new ResponseEntity<>(ErrorUtils.BAD_LOCALE, HttpStatus.NOT_FOUND); if (gender != null && gender != 1 && gender != 2) return new ResponseEntity<>(ErrorUtils.BAD_GENDER, HttpStatus.NOT_FOUND); try { userDAO.updateUser(user); } catch (Exception e) { return new ResponseEntity<>(ErrorUtils.FAILED_SEND_EMAIL, HttpStatus.INTERNAL_SERVER_ERROR); } } catch (IOException ex) { return new ResponseEntity<>(ErrorUtils.INCORRECT_JSON, HttpStatus.BAD_REQUEST); } return new ResponseEntity<>(HttpStatus.OK); }
From source file:fragment.web.ChannelControllerTest.java
@Test public void testCreateChannelGet() { try {/* w w w . j a va2s . c om*/ Boolean found = false; channelController.createChannel(map, response); Assert.assertNotSame(HttpStatus.PRECONDITION_FAILED.value(), response.getStatus()); List<Channel> channelList = (List<Channel>) map.get("channels"); for (Channel channel : channelList) { if (channelDAO.find(4L).getCode().equals(channel.getCode())) { found = true; } } Assert.assertTrue(found); Assert.assertEquals(currencyValueService.listActiveCurrencies(), map.get("currencies")); } catch (Exception e) { e.printStackTrace(); Assert.fail(e.getMessage()); } }
From source file:it.smartcommunitylab.carpooling.managers.CarPoolingManager.java
/** * Update Booking of Recurrent Travel + Instances. * // w ww . j a v a 2s.co m * @param recurrentTravel * @param reqBooking * @param userId * @return * @throws CarPoolingCustomException */ private RecurrentTravel updateRecurrentTravelBooking(RecurrentTravel recurrentTravel, RecurrentBooking reqBooking, String userId) throws CarPoolingCustomException { List<Travel> tranistInstances = travelRepository.findFutureInstanceOfRecurrTravel(recurrentTravel.getId()); if (tranistInstances != null && !tranistInstances.isEmpty()) { // booking instance to replicate. Booking instanceBooking = new Booking(); instanceBooking.setAccepted(0); instanceBooking.setTraveller(reqBooking.getTraveller()); instanceBooking.setRecurrent(true); instanceBooking.setDate(new java.util.Date(System.currentTimeMillis())); for (Travel instance : tranistInstances) { List<Booking> transitStateBooking = instance.getBookings(); int availability = instance.getPlaces(); if (transitStateBooking.isEmpty()) { // add new booking to instance. transitStateBooking.add(instanceBooking); } else { List<Booking> temp = new ArrayList<Booking>(); temp.addAll(transitStateBooking); boolean updatedNewBooking = false; for (Booking uBooking : temp) { if (uBooking.getTraveller().getUserId().equalsIgnoreCase(userId)) { // 1. check if user is present with recurrent // booking -> throw exception [USER ALREADY // BOOKED]. if (uBooking.isRecurrent()) { throw new CarPoolingCustomException(HttpStatus.FORBIDDEN.value(), "user has already booked."); } // 2. if user is present with non recurrent booking // -> override it. if (!uBooking.isRecurrent()) { transitStateBooking.remove(uBooking); uBooking.setRecurrent(true); uBooking.setAccepted(0); transitStateBooking.add(uBooking); updatedNewBooking = true; break; } } else if (uBooking.getAccepted() != -1) { availability--; // 3. if not present check for // availability } } if (availability < 1) { throw new CarPoolingCustomException(HttpStatus.PRECONDITION_FAILED.value(), "travel not bookable."); } if (!updatedNewBooking) { // add new booking to instance. transitStateBooking.add(instanceBooking); } } } // update recurrent travel. reqBooking.getTraveller().setUserId(userId); reqBooking.setAccepted(0); boolean alreadyBooked = false; List<RecurrentBooking> tmpList = new ArrayList<RecurrentBooking>(); if (recurrentTravel.getBookings() != null) tmpList.addAll(recurrentTravel.getBookings()); for (RecurrentBooking uBooking : tmpList) { if (userId.equals(uBooking.getTraveller().getUserId())) { alreadyBooked = true; // if in the past was rejected, allow for being re-booked // again? consider rejecting if (uBooking.getAccepted() == -1) { uBooking.setAccepted(0); reccurrentTravelRepository.save(recurrentTravel); } break; } } if (!alreadyBooked) { recurrentTravel.getBookings().add(reqBooking); reccurrentTravelRepository.save(recurrentTravel); } // update travel instances of recurrent travel. travelRepository.save(tranistInstances); // create notification. String targetUserId = recurrentTravel.getUserId(); Map<String, String> data = new HashMap<String, String>(); data.put("senderId", userId); User user = userRepository.findOne(userId); data.put("senderFullName", user.fullName()); // always notify with instance of recurrent travel. Notification bookingNotification = new Notification(targetUserId, CarPoolingUtils.NOTIFICATION_BOOKING, data, false, tranistInstances.get(0).getId(), System.currentTimeMillis()); notificationRepository.save(bookingNotification); // notify via parse. try { sendPushNotification.sendNotification(targetUserId, bookingNotification); } catch (JSONException e) { throw new CarPoolingCustomException(HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage()); } } else { throw new CarPoolingCustomException(HttpStatus.INTERNAL_SERVER_ERROR.value(), "no instance found for reccurrent travel."); } return recurrentTravel; }
From source file:it.smartcommunitylab.carpooling.managers.CarPoolingManager.java
public Travel bookNonRecurrent(String travelId, Booking reqBooking, String userId) throws CarPoolingCustomException { Travel travel = travelRepository.findOne(travelId); if (travel != null) { if (CarPoolingUtils.isValidUser(travel, userId, reqBooking)) { if (CarPoolingUtils.havePlaces(travel, reqBooking, userId)) { reqBooking.setRecurrent(false); reqBooking.getTraveller().setUserId(userId); reqBooking.setAccepted(0); reqBooking.setDate(new java.util.Date(System.currentTimeMillis())); travel.getBookings().add(reqBooking); // save travel. travelRepository.save(travel); } else { throw new CarPoolingCustomException(HttpStatus.PRECONDITION_FAILED.value(), "travel not bookable."); }// w w w . j a va 2 s . co m // create notification. String targetUserId = travel.getUserId(); Map<String, String> data = new HashMap<String, String>(); data.put("senderId", userId); User user = userRepository.findOne(userId); data.put("senderFullName", user.fullName()); Notification bookingNotification = new Notification(targetUserId, CarPoolingUtils.NOTIFICATION_BOOKING, data, false, travel.getId(), System.currentTimeMillis()); notificationRepository.save(bookingNotification); // notify via parse. try { sendPushNotification.sendNotification(targetUserId, bookingNotification); } catch (JSONException e) { throw new CarPoolingCustomException(HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage()); } } else { throw new CarPoolingCustomException(HttpStatus.FORBIDDEN.value(), "user has already booked."); } } else { throw new CarPoolingCustomException(HttpStatus.INTERNAL_SERVER_ERROR.value(), "travel not found."); } return travel; }
From source file:org.fao.geonet.api.userfeedback.UserFeedbackAPI.java
/** * New user feedback./* w ww .j a v a 2 s . c o m*/ * * @param userFeedbackDto the user feedback dto * @param httpSession the http session * @return the response entity * @throws Exception the exception */ @ApiOperation(value = "Creates a user feedback", notes = "Creates a user feedback in draft status if the user is not logged in.", nickname = "newUserFeedback") @RequestMapping(value = "/userfeedback", produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.POST) @ResponseStatus(HttpStatus.CREATED) @ResponseBody public ResponseEntity newUserFeedback(@ApiParam(name = "uf") @RequestBody UserFeedbackDTO userFeedbackDto, @ApiIgnore final HttpSession httpSession, @ApiIgnore final HttpServletRequest request) throws Exception { final ApplicationContext appContext = ApplicationContextHolder.get(); final SettingManager settingManager = appContext.getBean(SettingManager.class); final String functionEnabled = settingManager.getValue(Settings.SYSTEM_LOCALRATING_ENABLE); if (!functionEnabled.equals(RatingsSetting.ADVANCED)) { return new ResponseEntity(HttpStatus.FORBIDDEN); } try { final UserSession session = ApiUtils.getUserSession(httpSession); Locale locale = languageUtils.parseAcceptLanguage(request.getLocales()); ResourceBundle messages = ResourceBundle.getBundle("org.fao.geonet.api.Messages", locale); Log.debug("org.fao.geonet.api.userfeedback.UserFeedback", "newUserFeedback"); final IUserFeedbackService userFeedbackService = getUserFeedbackService(); boolean recaptchaEnabled = settingManager .getValueAsBool(Settings.SYSTEM_USERSELFREGISTRATION_RECAPTCHA_ENABLE); if (recaptchaEnabled) { boolean validRecaptcha = RecaptchaChecker.verify(userFeedbackDto.getCaptcha(), settingManager.getValue(Settings.SYSTEM_USERSELFREGISTRATION_RECAPTCHA_SECRETKEY)); if (!validRecaptcha) { return new ResponseEntity<>(messages.getString("recaptcha_not_valid"), HttpStatus.PRECONDITION_FAILED); } } userFeedbackService.saveUserFeedback(UserFeedbackUtils.convertFromDto(userFeedbackDto, session != null ? session.getPrincipal() : null), request.getRemoteAddr()); return new ResponseEntity(HttpStatus.CREATED); } catch (final Exception e) { e.printStackTrace(); throw e; } }
From source file:org.fao.geonet.api.userfeedback.UserFeedbackAPI.java
@ApiOperation(value = "Send an email to catalogue administrator or record's contact", notes = "", nickname = "sendEmailToContact") @RequestMapping(value = "/records/{metadataUuid}/alert", produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.POST) @ResponseStatus(HttpStatus.CREATED)// www.ja va 2 s. c o m @ResponseBody public ResponseEntity sendEmailToContact( @ApiParam(value = "Metadata record UUID.", required = true) @PathVariable(value = "metadataUuid") final String metadataUuid, @ApiParam(value = "Recaptcha validation key.", required = false) @RequestParam(required = false, defaultValue = "") final String recaptcha, @ApiParam(value = "User name.", required = true) @RequestParam final String name, @ApiParam(value = "User organisation.", required = true) @RequestParam final String org, @ApiParam(value = "User email address.", required = true) @RequestParam final String email, @ApiParam(value = "A comment or question.", required = true) @RequestParam final String comments, @ApiParam(value = "User phone number.", required = false) @RequestParam(required = false, defaultValue = "") final String phone, @ApiParam(value = "Email subject.", required = false) @RequestParam(required = false, defaultValue = "User feedback") final String subject, @ApiParam(value = "User function.", required = false) @RequestParam(required = false, defaultValue = "-") final String function, @ApiParam(value = "Comment type.", required = false) @RequestParam(required = false, defaultValue = "-") final String type, @ApiParam(value = "Comment category.", required = false) @RequestParam(required = false, defaultValue = "-") final String category, @ApiParam(value = "List of record's contact to send this email.", required = false) @RequestParam(required = false, defaultValue = "") final String metadataEmail, @ApiIgnore final HttpServletRequest request) throws IOException { ConfigurableApplicationContext applicationContext = ApplicationContextHolder.get(); SettingManager sm = applicationContext.getBean(SettingManager.class); MetadataRepository metadataRepository = applicationContext.getBean(MetadataRepository.class); Locale locale = languageUtils.parseAcceptLanguage(request.getLocales()); ResourceBundle messages = ResourceBundle.getBundle("org.fao.geonet.api.Messages", locale); boolean recaptchaEnabled = sm.getValueAsBool(Settings.SYSTEM_USERSELFREGISTRATION_RECAPTCHA_ENABLE); if (recaptchaEnabled) { boolean validRecaptcha = RecaptchaChecker.verify(recaptcha, sm.getValue(Settings.SYSTEM_USERSELFREGISTRATION_RECAPTCHA_SECRETKEY)); if (!validRecaptcha) { return new ResponseEntity<>(messages.getString("recaptcha_not_valid"), HttpStatus.PRECONDITION_FAILED); } } String to = sm.getValue(SYSTEM_FEEDBACK_EMAIL); String catalogueName = sm.getValue(SYSTEM_SITE_NAME_PATH); List<String> toAddress = new LinkedList<String>(); toAddress.add(to); if (isNotBlank(metadataEmail)) { //Check metadata email belongs to metadata security!! Metadata md = metadataRepository.findOneByUuid(metadataUuid); if (md.getData().indexOf(metadataEmail) > 0) { toAddress.add(metadataEmail); } } String title = XslUtil.getIndexField(null, metadataUuid, "title", ""); MailUtil.sendMail(toAddress, String.format(messages.getString("user_feedback_title"), catalogueName, title, subject), String.format(messages.getString("user_feedback_text"), name, org, function, email, phone, title, type, category, comments, sm.getNodeURL(), metadataUuid), sm); return new ResponseEntity(HttpStatus.CREATED); }
From source file:org.geoserver.opensearch.rest.CollectionsController.java
private void configureSeparateBandsMosaic(String collection, CollectionLayer layerConfiguration, String relativePath, Resource mosaicDirectory) throws Exception { // get the namespace URI for the store final FeatureSource<FeatureType, Feature> collectionSource = getOpenSearchAccess().getCollectionSource(); final FeatureType schema = collectionSource.getSchema(); final String nsURI = schema.getName().getNamespaceURI(); // image mosaic won't automatically create the mosaic config for us in this case, // we have to setup both the mosaic property file and sample image for all bands for (int band : layerConfiguration.getBands()) { final String mosaicName = collection + OpenSearchAccess.BAND_LAYER_SEPARATOR + band; // get the sample granule File file = getSampleGranule(collection, nsURI, band, mosaicName); AbstractGridFormat format = (AbstractGridFormat) GridFormatFinder.findFormat(file, EXCLUDE_MOSAIC_HINTS);// w w w . j a va 2 s.c o m if (format == null) { throw new RestException( "Could not find a coverage reader able to process " + file.getAbsolutePath(), HttpStatus.PRECONDITION_FAILED); } ImageLayout imageLayout; double[] nativeResolution; AbstractGridCoverage2DReader reader = null; try { reader = format.getReader(file); if (reader == null) { throw new RestException( "Could not find a coverage reader able to process " + file.getAbsolutePath(), HttpStatus.PRECONDITION_FAILED); } imageLayout = reader.getImageLayout(); nativeResolution = reader.getResolutionLevels()[0]; } finally { if (reader != null) { reader.dispose(); } } ImageReaderSpi spi = null; try (FileImageInputStream fis = new FileImageInputStream(file)) { ImageReader imageReader = ImageIOExt.getImageioReader(fis); if (imageReader != null) { spi = imageReader.getOriginatingProvider(); } } // the mosaic configuration Properties mosaicConfig = new Properties(); mosaicConfig.put("Levels", nativeResolution[0] + "," + nativeResolution[1]); mosaicConfig.put("Heterogeneous", "true"); mosaicConfig.put("AbsolutePath", "true"); mosaicConfig.put("Name", "" + band); mosaicConfig.put("TypeName", mosaicName); mosaicConfig.put("TypeNames", "false"); // disable typename scanning mosaicConfig.put("Caching", "false"); mosaicConfig.put("LocationAttribute", "location"); mosaicConfig.put("TimeAttribute", TIME_START); mosaicConfig.put("CanBeEmpty", "true"); if (spi != null) { mosaicConfig.put("SuggestedSPI", spi.getClass().getName()); } // TODO: the index is now always in 4326, so the mosaic has to be heterogeneous // in general, unless we know the data is uniformly in something else, in that // case we could reproject the view reporting the footprints... // if (layerConfiguration.isHeterogeneousCRS()) { mosaicConfig.put("HeterogeneousCRS", "true"); mosaicConfig.put("MosaicCRS", "EPSG:4326" /* layerConfiguration.getMosaicCRS() */); mosaicConfig.put("CrsAttribute", "crs"); // } Resource propertyResource = mosaicDirectory.get(band + ".properties"); try (OutputStream os = propertyResource.out()) { mosaicConfig.store(os, "DataStore configuration for collection '" + collection + "' and band '" + band + "'"); } // create the sample image Resource sampleImageResource = mosaicDirectory.get(band + Utils.SAMPLE_IMAGE_NAME); Utils.storeSampleImage(sampleImageResource.file(), imageLayout.getSampleModel(null), imageLayout.getColorModel(null)); } // this is ridicolous, but for the moment, multi-crs mosaics won't work if there // is no indexer.properties around, even if no collection is actually done buildIndexer(collection, mosaicDirectory); // mosaic datastore connection createDataStoreProperties(collection, mosaicDirectory); // the mosaic datastore itself CatalogBuilder cb = new CatalogBuilder(catalog); CoverageStoreInfo mosaicStoreInfo = createMosaicStore(cb, collection, layerConfiguration, relativePath); // and finally the layer, with a coverage view associated to it List<CoverageBand> coverageBands = buildCoverageBands(layerConfiguration); final String coverageName = layerConfiguration.getLayer(); final CoverageView coverageView = new CoverageView(coverageName, coverageBands); CoverageInfo coverageInfo = coverageView.createCoverageInfo(coverageName, mosaicStoreInfo, cb); timeEnableResource(coverageInfo); final LayerInfo layerInfo = cb.buildLayer(coverageInfo); catalog.add(coverageInfo); catalog.add(layerInfo); // configure the style if needed createStyle(layerConfiguration, layerInfo); }
From source file:org.geoserver.opensearch.rest.CollectionsController.java
private void configureSimpleMosaic(String collection, CollectionLayer layerConfiguration, final String relativePath, Resource mosaic) throws IOException, Exception { // make sure there is at least one granule final FeatureSource<FeatureType, Feature> collectionSource = getOpenSearchAccess().getCollectionSource(); final FeatureType schema = collectionSource.getSchema(); final String nsURI = schema.getName().getNamespaceURI(); final NameImpl fsName = new NameImpl(nsURI, collection); final FeatureSource<FeatureType, Feature> genericGranuleSource = getOpenSearchAccess() .getFeatureSource(fsName);/*from w ww . jav a 2s .c o m*/ SimpleFeatureSource granuleSource = DataUtilities.simple(genericGranuleSource); SimpleFeature firstFeature = DataUtilities.first(granuleSource.getFeatures()); if (firstFeature == null) { throw new RestException("Cannot configure a mosaic, please add at least one product " + "with granules in order to set it up", HttpStatus.PRECONDITION_FAILED); } buildIndexer(collection, mosaic); createDataStoreProperties(collection, mosaic); CatalogBuilder cb = new CatalogBuilder(catalog); createMosaicStore(cb, collection, layerConfiguration, relativePath); // and then the layer CoverageInfo coverageInfo = cb.buildCoverage(collection); coverageInfo.setName(layerConfiguration.getLayer()); timeEnableResource(coverageInfo); catalog.add(coverageInfo); LayerInfo layerInfo = cb.buildLayer(coverageInfo); catalog.add(layerInfo); // configure the style if needed createStyle(layerConfiguration, layerInfo); }
From source file:org.venice.beachfront.bfapi.services.IABrokerPassthroughService.java
public ResponseEntity<String> passthroughRequest(HttpMethod method, HttpServletRequest request) throws MalformedURLException, IOException, URISyntaxException, UserException { // URI to ia-Broker will strip out the /ia prefix that the bf-api uses to denote ia-broker proxying // Single data source right now, which is planet. In the future, we will switch on the sensor/item type to // determine the source (or have the source just injected) String requestPath = request.getRequestURI().replaceAll("/ia/", "/"); URI uri = new URI(IA_BROKER_PROTOCOL, null, IA_BROKER_SERVER, IA_BROKER_PORT, requestPath, request.getQueryString(), null); String body = IOUtils.toString(request.getReader()); piazzaLogger.log(String.format("Proxying request to IA Broker at URI %s", uri.toString()), Severity.INFORMATIONAL); try {/*from w w w . j a v a2 s . c o m*/ ResponseEntity<String> response = restTemplate.exchange(uri, method, new HttpEntity<String>(body), String.class); piazzaLogger.log( String.format("Received IA Broker response, code=%d, length=%d, for URI %s", response.getStatusCodeValue(), response.getBody() == null ? 0 : response.getBody().length(), uri.toString()), Severity.INFORMATIONAL); return response; } catch (HttpClientErrorException | HttpServerErrorException exception) { piazzaLogger.log(String.format("Received IA Broker error response, code=%d, length=%d, for URI %s", exception.getStatusCode().value(), exception.getResponseBodyAsString().length(), uri.toString()), Severity.ERROR); if (exception.getStatusCode().equals(HttpStatus.UNAUTHORIZED) || exception.getStatusCode().equals(HttpStatus.FORBIDDEN)) { throw new UserException(exception.getResponseBodyAsString(), exception, exception.getResponseBodyAsString(), HttpStatus.PRECONDITION_FAILED); } throw new UserException("Upstream image broker error", exception, exception.getResponseBodyAsString(), exception.getStatusCode()); } }