/** * Adds a trust bundle to the system. * * @param uriInfo Injected URI context used for building the location URI. * @param bundle The bundle to add to the system. * @return Status of 201 if the bundle was added or a status of 409 if a bundle with the same name * already exists. */ @PUT @Consumes(MediaType.APPLICATION_JSON) public Response addTrustBundle(@Context UriInfo uriInfo, TrustBundle bundle) { // make sure it doesn't exist try { if (bundleDao.getTrustBundleByName(bundle.getBundleName()) != null) return Response.status(Status.CONFLICT).cacheControl(noCache).build(); } catch (Exception e) { log.error("Error looking up bundle.", e); return Response.serverError().cacheControl(noCache).build(); } try { final org.nhindirect.config.store.TrustBundle entityBundle = EntityModelConversion.toEntityTrustBundle(bundle); bundleDao.addTrustBundle(entityBundle); final UriBuilder newLocBuilder = uriInfo.getBaseUriBuilder(); final URI newLoc = newLocBuilder.path("trustbundle/" + bundle.getBundleName()).build(); // the trust bundle does not contain any of the anchors // they must be fetched from the URL... use the // refresh route to force downloading the anchors template.sendBody(entityBundle); return Response.created(newLoc).cacheControl(noCache).build(); } catch (Exception e) { log.error("Error adding trust bundle.", e); return Response.serverError().cacheControl(noCache).build(); } }
@POST @Path("add") @Produces(MediaType.TEXT_PLAIN) public Response add( @FormParam("gasAcctId") final int gasAcctId, @FormParam("reading") final int reading, @FormParam("readDate") final Date readDate) { try { if (!SecurityContextHolder.getContext() .getAuthentication() .getName() .equals(gasDAO.getAccount(gasAcctId).getUsername())) { return Response.status(406).entity("Resource identity not correct.").build(); } } catch (DataAccessException e) { return Response.serverError().entity("Failed to retrieve resource identity.").build(); } GasReading gasReading = new GasReading(); gasReading.setGasAcctId(gasAcctId); gasReading.setReading(reading); gasReading.setReadDate(readDate); try { return Response.status(201).entity(String.valueOf(gasRDAO.addReading(gasReading))).build(); } catch (DataAccessException e) { return Response.serverError().entity("Server error.").build(); } }
// TODO @GET @Path("/jobQueue/{jobID}") // @Produces(MediaType.TEXT_XML) public Response checkJobQueue(@PathParam("jobID") String jobID) { // does job exist? System.out.println("[checkJobQueue] queue length = " + jobqueue.size()); System.out.println("[checkJobQueue] jobID = " + jobID); if (jobqueue.containsKey(UUID.fromString(jobID))) { System.out.println("Found job ID"); // if job is not finished yet return 200 if (jobqueue.get(UUID.fromString(jobID)).getStatus() == SFPGenJob.PROCESSING) return Response.status(Status.OK) .entity("Still processing - please check back later.") .build(); // if job is finished and SFP has been created else { // return path to SFP resource URI sfp_uri; try { sfp_uri = new URI("SFP/sfplist/" + jobID); // update jobQueue SFPGenJob currjob = jobqueue.get(UUID.fromString(jobID)); currjob.updateStatus(SFPGenJob.GONE); jobqueue.put(UUID.fromString(jobID), currjob); return Response.status(Status.SEE_OTHER).location(sfp_uri).build(); } catch (URISyntaxException e) { // TODO Auto-generated catch block e.printStackTrace(); } return Response.serverError().build(); } } else return Response.serverError().entity("No such job ID").build(); }
/** * Updates the signing certificate of a trust bundle. * * @param bundleName The name of the trust bundle to update. * @param certData A DER encoded representation of the new signing certificate. * @return Status of 204 if the trust bundle's signing certificate was updated, status of 400 if * the signing certificate is invalid, or a status 404 if a trust bundle with the given name * does not exist. */ @POST @Path("{bundle}/signingCert") @Consumes(MediaType.APPLICATION_JSON) public Response updateSigningCert(@PathParam("bundle") String bundleName, byte[] certData) { X509Certificate signingCert = null; if (certData.length > 0) { try { signingCert = CertUtils.toX509Certificate(certData); } catch (CertificateConversionException ex) { log.error("Signing certificate is not in a valid format " + bundleName, ex); return Response.status(Status.BAD_REQUEST).cacheControl(noCache).build(); } } // make sure the bundle exists org.nhindirect.config.store.TrustBundle entityBundle; try { entityBundle = bundleDao.getTrustBundleByName(bundleName); if (entityBundle == null) return Response.status(Status.NOT_FOUND).cacheControl(noCache).build(); } catch (Exception e) { log.error("Error looking up bundle.", e); return Response.serverError().cacheControl(noCache).build(); } // now update try { bundleDao.updateTrustBundleSigningCertificate(entityBundle.getId(), signingCert); return Response.noContent().cacheControl(noCache).build(); } catch (Exception e) { log.error("Error updating trust bundle signing certificate.", e); return Response.serverError().cacheControl(noCache).build(); } }
@GET @Path("cookies/{cookieName}") @Produces("text/plain") public String getCookies( @Context HttpHeaders headers, @PathParam("cookieName") String cookieName) { final Map<String, Cookie> cookies = headers.getCookies(); try { cookies.put("notAllowed", new Cookie("notAllowed", "value")); throw new WebApplicationException( Response.serverError().entity("could add cookie notAllowed").build()); } catch (UnsupportedOperationException uoe) { // not allowed } try { cookies.put("xyz", new Cookie("notAllowed", "value")); throw new WebApplicationException(Response.serverError().entity("could add xyz").build()); } catch (UnsupportedOperationException uoe) { // not allowed } final Cookie cookie = cookies.get(cookieName); if (cookie == null) { return null; } return cookie.toString(); }
/** * Updates multiple bundle attributes. If the URL of the bundle changes, then the bundle is * automatically refreshed. * * @param bundleName The name of the bundle to update. * @param bundleData The data of the trust bundle to update. Empty or null attributes indicate * that the attribute should not be changed. * @return Status of 204 if the bundle attributes were updated, status of 400 if the signing * certificate is invalid, or a status 404 if a trust bundle with the given name does not * exist. */ @POST @Path("{bundle}/bundleAttributes") @Consumes(MediaType.APPLICATION_JSON) public Response updateBundleAttributes( @PathParam("bundle") String bundleName, TrustBundle bundleData) { // make sure the bundle exists org.nhindirect.config.store.TrustBundle entityBundle; try { entityBundle = bundleDao.getTrustBundleByName(bundleName); if (entityBundle == null) return Response.status(Status.NOT_FOUND).cacheControl(noCache).build(); } catch (Exception e) { log.error("Error looking up bundle.", e); return Response.serverError().cacheControl(noCache).build(); } final String oldBundleURL = entityBundle.getBundleURL(); // if there is a signing certificate in the request, make sure it's valid X509Certificate newSigningCert = null; if (bundleData.getSigningCertificateData() != null) { try { newSigningCert = CertUtils.toX509Certificate(bundleData.getSigningCertificateData()); } catch (CertificateConversionException ex) { log.error("Signing certificate is not in a valid format " + bundleName, ex); return Response.status(Status.BAD_REQUEST).cacheControl(noCache).build(); } } // update the bundle try { bundleDao.updateTrustBundleAttributes( entityBundle.getId(), bundleData.getBundleName(), bundleData.getBundleURL(), newSigningCert, bundleData.getRefreshInterval()); // if the URL changed, the bundle needs to be refreshed if (bundleData.getBundleURL() != null && !bundleData.getBundleURL().isEmpty() && !oldBundleURL.equals(bundleData.getBundleURL())) { entityBundle = bundleDao.getTrustBundleById(entityBundle.getId()); template.sendBody(entityBundle); } return Response.noContent().cacheControl(noCache).build(); } catch (Exception e) { log.error("Error updating trust bundle attributes.", e); return Response.serverError().cacheControl(noCache).build(); } }
/** * Gets all trust bundles associated to a domain. * * @param domainName The name of the domain to fetch trust bundles for. * @param fetchAnchors Indicates if the retrieval should also include the trust anchors in the * bundle. When only needing bundle names, this parameter should be set to false for better * performance. * @return A JSON representation of a collection of trust bundle that are associated to the given * domain. Returns a status of 404 if a domain with the given name does not exist or a status * of 404 if no trust bundles are associated with the given name. */ @GET @Produces(MediaType.APPLICATION_JSON) @Path("domains/{domainName}") public Response getTrustBundlesByDomain( @PathParam("domainName") String domainName, @QueryParam("fetchAnchors") @DefaultValue("true") boolean fetchAnchors) { // make sure the domain exists org.nhindirect.config.store.Domain entityDomain; try { entityDomain = domainDao.getDomainByName(domainName); if (entityDomain == null) return Response.status(Status.NOT_FOUND).cacheControl(noCache).build(); } catch (Exception e) { log.error("Error looking up domain.", e); return Response.serverError().cacheControl(noCache).build(); } Collection<org.nhindirect.config.store.TrustBundleDomainReltn> retBundles = null; try { retBundles = bundleDao.getTrustBundlesByDomain(entityDomain.getId()); if (retBundles.isEmpty()) return Response.noContent().cacheControl(noCache).build(); } catch (Throwable e) { log.error("Error looking up trust bundles", e); return Response.serverError().cacheControl(noCache).build(); } final Collection<TrustBundleDomainReltn> modelBundles = new ArrayList<TrustBundleDomainReltn>(); for (org.nhindirect.config.store.TrustBundleDomainReltn bundleReltn : retBundles) { if (!fetchAnchors) bundleReltn.getTrustBundle().setTrustBundleAnchors(new ArrayList<TrustBundleAnchor>()); final TrustBundleDomainReltn newReltn = new TrustBundleDomainReltn(); newReltn.setIncoming(bundleReltn.isIncoming()); newReltn.setOutgoing(bundleReltn.isOutgoing()); newReltn.setDomain(EntityModelConversion.toModelDomain(bundleReltn.getDomain())); newReltn.setTrustBundle( EntityModelConversion.toModelTrustBundle(bundleReltn.getTrustBundle())); modelBundles.add(newReltn); } final GenericEntity<Collection<TrustBundleDomainReltn>> entity = new GenericEntity<Collection<TrustBundleDomainReltn>>(modelBundles) {}; return Response.ok(entity).cacheControl(noCache).build(); }
/** * Builds the response to reset the password of a user * * @param username - Username of the user. * @param credentials - User credentials * @return Response Object */ public static Response buildResetPasswordResponse( String username, PasswordResetWrapper credentials) { try { UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager(); if (!userStoreManager.isExistingUser(username)) { return Response.status(Response.Status.BAD_REQUEST) .entity( new ErrorResponse.ErrorResponseBuilder() .setMessage("No user found with the username " + username) .build()) .build(); } if (credentials == null || credentials.getNewPassword() == null) { return Response.status(Response.Status.BAD_REQUEST) .entity( new ErrorResponse.ErrorResponseBuilder() .setMessage("Password cannot be empty." + username) .build()) .build(); } if (!validateCredential(credentials.getNewPassword())) { String errorMsg = DeviceMgtAPIUtils.getRealmService() .getBootstrapRealmConfiguration() .getUserStoreProperty(PASSWORD_VALIDATION_ERROR_MSG_TAG); return Response.status(Response.Status.BAD_REQUEST) .entity(new ErrorResponse.ErrorResponseBuilder().setMessage(errorMsg).build()) .build(); } userStoreManager.updateCredentialByAdmin(username, credentials.getNewPassword()); return Response.status(Response.Status.OK) .entity("UserImpl password by username: "******" was successfully changed.") .build(); } catch (UserStoreException e) { String msg = "Error occurred while updating the credentials of user '" + username + "'"; log.error(msg, e); return Response.serverError() .entity(new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()) .build(); } catch (UnsupportedEncodingException e) { String msg = "Could not change the password of the user: "******". The Character Encoding is not supported."; log.error(msg, e); return Response.serverError() .entity(new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()) .build(); } }
@POST @Path("/add") @Consumes("multipart/form-data") public Response addSite(@MultipartForm AddSiteForm form) { Response ret; try { Site site = new Site(); site.setName(form.getName()); site.setAddress(form.getAddress()); Double[] coordinates = new Double[2]; coordinates[1] = Double.valueOf(form.getLatitude()); coordinates[0] = Double.valueOf(form.getLongitude()); site.setCoordinates(coordinates); site.setDescription(form.getDescription()); site.setImage(form.getImageData()); site.setRadius(Integer.valueOf(form.getRadius())); if (form.getTags() != null && !form.getTags().isEmpty()) { site.setName(form.getName()); String[] tagsStr = form.getTags().trim().split(","); for (String tagStr : tagsStr) { Tag tag = new Tag(); tag.setName(tagStr.trim()); site.addTag(tag); } } SitesController.getInstance().NewSite(site); ret = Response.seeOther(new URI("../GeoRedUy.BackEnd/site?ListSites")).build(); } catch (Exception e) { e.printStackTrace(); ret = Response.serverError().entity(e.getMessage()).build(); } return ret; }
@PUT @Path("update/{id}") @Consumes("application/x-www-form-urlencoded") @Produces(MediaType.APPLICATION_XML) public Response updateGroup( @PathParam("id") int groupId, @FormParam("groupName") String groupName) throws SQLException { Session session = null; Group mappedGroup = new Group(); try { session = HibernateUtil.getSessionFactory().openSession(); Group group = session.load(Group.class, groupId); session.beginTransaction(); group.setGroupName(groupName); session.getTransaction().commit(); Mapper mapper = new DozerBeanMapper(); mappedGroup = mapper.map(group, Group.class); } catch (Exception e) { System.err.println("updateGroup failed, " + e.getMessage()); return Response.serverError().build(); } finally { if (session != null && session.isOpen()) { session.close(); } } return Response.ok(mappedGroup).build(); }
// <editor-fold defaultstate="collapsed" desc="import"> @POST @Path("/import/zip") @Consumes(MediaType.MULTIPART_FORM_DATA) public Response importZip( @FormDataParam("file") FormDataContentDisposition fileDisposition, @FormDataParam("file") InputStream file) { String storeDirPath = Init.getStoredQueriesPath(); File storeDir = storeDirPath == null ? null : new File(storeDirPath); if (storeDir == null) return Response.status(Response.Status.NOT_FOUND).build(); final StringBuilder res = new StringBuilder(); if (fileDisposition != null) { logInfo("import {0}", fileDisposition.getFileName()); try { unzip( storeDir, file, new Reciver<String>() { @Override public void recive(String logtext) { res.append(logtext.trim()); res.append("\n"); } }); } catch (IOException ex) { Logger.getLogger(SqlQueriesRest.class.getName()).log(Level.SEVERE, null, ex); return Response.serverError().build(); } } return Response.ok("succ\n" + res.toString()).build(); }
@POST public Response create( @Context HttpHeaders headers, @QueryParam("durable") Boolean durable, @QueryParam("expiration") Long expiration, @QueryParam("priority") Integer priority, @Context UriInfo uriInfo, byte[] body) { try { boolean isDurable = defaultDurable; if (durable != null) { isDurable = durable.booleanValue(); } publish(headers, body, isDurable, expiration, priority); } catch (Exception e) { Response error = Response.serverError() .entity("Problem posting message: " + e.getMessage()) .type("text/plain") .build(); throw new WebApplicationException(e, error); } Response.ResponseBuilder builder = Response.status(201); UriBuilder nextBuilder = uriInfo.getAbsolutePathBuilder(); URI next = nextBuilder.build(); serviceManager .getLinkStrategy() .setLinkHeader(builder, "create-next", "create-next", next.toString(), "*/*"); return builder.build(); }
@GET @Path("resumeWebApplicationException") public String resumeWebApplicationException() throws Exception { return resume( new WebApplicationException( Response.serverError().entity("resumeWebApplicationException").build())); }
@GET @Path("/all/{repoName}") public Response getCategory(@PathParam("repoName") String repoName) { List<CategoryNode> listCategoryNode = new ArrayList<CategoryNode>(); if (repoName == null || repoName.trim().isEmpty()) { return Response.status(HTTPStatus.NOT_FOUND) .entity(new RepositoryException("Can't find repository")) .build(); } // Get all category try { if (documentTypes.isEmpty()) documentTypes = templateService_.getAllDocumentNodeTypes(repoName); List<Node> categoryNodes = taxonomyService_.getAllTaxonomyTrees(repoName); for (Node rootCategoryNode : categoryNodes) { getTaxnomyNodeRescursive(rootCategoryNode, rootCategoryNode, listCategoryNode); } } catch (Exception e) { LOG.error(e); return Response.serverError().build(); } ListResultNode listResultNode = new ListResultNode(); listResultNode.setLstNode(listCategoryNode); return Response.ok(listResultNode, new MediaType("application", "json")).build(); }
/** * This method handles HTTP POST requests with JSON data. It sends an add operation to the * listener passing it the JSON data. * * @param json A string in JSON format. * @return Response with the appropriate HTTP code. */ @POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response add(String json) { RestListener listener = RestManager.getListener(); Response response; try { log.info("Add request with json: {}", json); listener.add(parseMap(json)); response = Response.ok().build(); } catch (RestInvalidException e) { log.info("Add request was invalid: {}", e.getMessage()); response = Response.status(Response.Status.BAD_REQUEST) .entity(toMap(e, Response.Status.BAD_REQUEST)) .build(); } catch (Exception e) { e.printStackTrace(); response = Response.serverError().entity(toMap(e, Response.Status.INTERNAL_SERVER_ERROR)).build(); } return response; }
@POST @Path("/{registrationId}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response postUpdate( @Context HttpServletRequest request, @PathParam("registrationId") UUID id, String body) throws Exception { authService.guardAuthenticatedUser(request); Either<String, RegistrationsUpdate> map = ArgoUtils.parseEither(body) .right() .map(x -> x.getNode("tuple")) .right() .bind(RegistrationsRestService::registrationsUpdate); if (map.isLeft()) return Response.serverError().build(); RegistrationsUpdate ru = map.right().value(); try (Connection c = dataSource.getConnection()) { c.setAutoCommit(false); if (!registrationsSqlMapper.one(c, id).isSome()) return Response.status(Status.NOT_FOUND).build(); registrationsSqlMapper.update( c, id, ru.billingCompany, ru.badge, ru.dietaryRequirements, ru.bundle); c.commit(); } return Response.ok().build(); }
@GET // @Produces( "text/tab-separated-values" ) @Path("{id}/export") public final Response export( @PathParam("id") long id, @Context HttpServletRequest httpRequest, @Context HttpServletResponse httpResponse) { try { final FormBean form = dbManager.selectFormBean(id); if (form == null) { return Response.status(Status.NOT_FOUND).build(); } final List<CollectionBean> collections = dbManager.selectCollectionBeanList(id); if (collections.isEmpty()) { return Response.noContent().build(); } form.setCollections(collections); final String date = String.format("%tF_%<tH-%<tM-%<tS", Calendar.getInstance().getTime()); final String filename = String.format("collections_form%s_%s", id, date); final String contentDisposition = String.format("attachment; filename=\"%s.tsv\"", filename); httpResponse.addHeader("Content-Disposition", contentDisposition); httpResponse.addHeader("Cache-Control", "no-cache"); final ServletOutputStream out = httpResponse.getOutputStream(); final OutputStreamWriter writer = new OutputStreamWriter(out, Charset.forName("UTF-16LE")); Exporter.writeTsv(writer, form); return Response.ok().build(); } catch (final Throwable e) { logger.error("Error exporting collections", e); return Response.serverError().build(); } }
@GET @Produces(MediaType.TEXT_HTML) public Response detailView(@Context HttpServletRequest request) { ModelAndView view; ModelMap model = new ModelMap(); ResponseBuilder builder; try { model.addAttribute("title", "Account Settings - " + getContextName()); model.addAttribute("user", getCurrentUser()); model.addAttribute("currentView", "detail"); addFlashMessage(request, model); view = new ModelAndView("user.detail", model); builder = Response.ok(); } catch (UserNotFoundException e) { logger.warn("User not found", e); view = buildErrorView(Status.INTERNAL_SERVER_ERROR, e.getMessage()); builder = Response.serverError(); } return builder.entity(view).build(); }
/** * Return detailed information about the version whose id is passed as path argument. Returns a * JSON map with the fields id, creator, date, added_triples, removed_triples. Triple will be * represented in RDF/JSON format. @HTTP 404 in case the requested version does not exist * * @param id the ID of the version to return * @return a JSON map representing the version information as described above */ @GET @Produces("application/json") @Path("/versions/{id:[0-9]+}") public Response getVersion(@PathParam("id") Long id) { try { Version version = versioningService.getVersion(id); if (version != null) { Map<String, Object> result = new HashMap<String, Object>(); result.put("id", version.getId()); if (version.getCreator() != null) { result.put("creator", version.getCreator().stringValue()); } result.put("date", DateUtils.ISO8601FORMAT.format(version.getCommitTime())); result.put("added_triples", JSONUtils.serializeTriplesAsJson(version.getAddedTriples())); result.put( "removed_triples", JSONUtils.serializeTriplesAsJson(version.getRemovedTriples())); return Response.ok().entity(result).build(); } else { return Response.status(Response.Status.NOT_FOUND) .entity("version with id " + id + " does not exist") .build(); } } catch (SailException e) { return Response.serverError() .entity("error loading version " + id + ": " + e.getMessage()) .build(); } }
/** * This methods handles HTTP DELETE requests. It sends an remove operation to the listener passing * it an ID. * * @param id The ID sent by the user on the request * @return Response with the appropriate HTTP code. */ @DELETE @Path("/{id}") @Produces(MediaType.APPLICATION_JSON) public Response remove(@PathParam("id") String id) { RestListener listener = RestManager.getListener(); Response response; // Check if the listener accepted the operation try { log.info("Remove request with id: {}", id); listener.remove(id); response = Response.ok().build(); } catch (RestNotFoundException e) { log.info("Remove request invalid: {}", e.getMessage()); e.printStackTrace(); response = Response.status(Response.Status.NOT_FOUND) .entity(toMap(e, Response.Status.NOT_FOUND)) .build(); } catch (Exception e) { e.printStackTrace(); response = Response.serverError().entity(toMap(e, Response.Status.INTERNAL_SERVER_ERROR)).build(); } return response; }
/** * Gets all trust bundles in the system. * * @param fetchAnchors Indicates if the retrieval should also include the trust anchors in the * bundle. When only needing bundle names, this parameter should be set to false for better * performance. * @return A JSON representation of a collection of all trust bundles in the system. Returns a * status of 204 if no trust bundles exist. */ @GET @Produces(MediaType.APPLICATION_JSON) public Response getTrustBundles( @QueryParam("fetchAnchors") @DefaultValue("true") boolean fetchAnchors) { Collection<org.nhindirect.config.store.TrustBundle> retBundles = null; try { retBundles = bundleDao.getTrustBundles(); if (retBundles.isEmpty()) return Response.noContent().cacheControl(noCache).build(); } catch (Throwable e) { log.error("Error looking up trust bundles", e); return Response.serverError().cacheControl(noCache).build(); } final Collection<TrustBundle> modelBundles = new ArrayList<TrustBundle>(); for (org.nhindirect.config.store.TrustBundle bundle : retBundles) { if (!fetchAnchors) bundle.setTrustBundleAnchors(new ArrayList<TrustBundleAnchor>()); modelBundles.add(EntityModelConversion.toModelTrustBundle(bundle)); } final GenericEntity<Collection<TrustBundle>> entity = new GenericEntity<Collection<TrustBundle>>(modelBundles) {}; return Response.ok(entity).cacheControl(noCache).build(); }
@GET @Path("/slack") public Response authenticateSlack( @QueryParam("code") String code, @QueryParam("state") String state) throws JSONException { JSONObject accessJO = null; JSONObject userJO = null; try { accessJO = getAccessToken(code); String token = accessJO.getString("access_token"); userJO = getUser(token); } catch (Exception ex) { return Response.serverError().status(500).entity(ex.getMessage()).build(); } try { sendToObjectManger(accessJO, userJO); } catch (Exception e) { System.out.println("Error to start the connection : solve this" + e.getMessage()); } return Response.ok("Congratulations !!!! Memory box Application is installed .").build(); }
@POST @Path("/topology/shift") @Produces(MediaType.TEXT_HTML) @Consumes(MediaType.APPLICATION_FORM_URLENCODED) public Response shiftTopologies( @FormParam("logicalName") String logicalName, @FormParam("direction") int direction, @FormParam("unhealthyPct") @DefaultValue("0.24") float unhealthyPct, @FormParam("probability") @DefaultValue("0.10") float probability) { try { ShiftPredicate shiftPredicate; boolean caterpillar; if (direction == 0) { // "zero" means evac caterpillar = false; shiftPredicate = new UnhealthyTopologyShiftPredicate(unhealthyPct); // TODO should be passed in } else { // "non-zero" means shift by N places caterpillar = true; shiftPredicate = new RandomShiftPredicate(probability); } rebalanceDirector.shiftTopologies( Optional.of(new MiruHost(logicalName)), shiftPredicate, new CaterpillarSelectHostsStrategy(caterpillar, direction, false)); return Response.ok("success").build(); } catch (Throwable t) { LOG.error( "POST /topology/shift {} {} {} {} {}", new Object[] {logicalName, direction, unhealthyPct, probability}, t); return Response.serverError().entity(t.getMessage()).build(); } }
public Response toResponse(QueryException exception) { return Response.serverError() .entity( String.format("%s\n%s\n", exception.getMessage(), exception.getCause().getMessage())) .type(MediaType.TEXT_PLAIN) .build(); }
@Override public Response createPoly(byte[] inputToAutodetectType) { log.debug("Creating app from autodetecting input"); boolean looksLikeLegacy = false; Exception legacyFormatException = null; // attempt legacy format try { ApplicationSpec appSpec = mapper().readValue(inputToAutodetectType, ApplicationSpec.class); if (appSpec.getType() != null || appSpec.getEntities() != null) { looksLikeLegacy = true; } return createFromAppSpec(appSpec); } catch (Exception e) { Exceptions.propagateIfFatal(e); legacyFormatException = e; log.debug("Input is not legacy ApplicationSpec JSON (will try others): " + e, e); } // TODO infer encoding from request String potentialYaml = new String(inputToAutodetectType); EntitySpec<? extends Application> spec = createEntitySpecForApplication(potentialYaml); // TODO not json - try ZIP, etc if (spec != null) { return launch(potentialYaml, spec); } else if (looksLikeLegacy) { throw Throwables.propagate(legacyFormatException); } else { return Response.serverError().entity("Unsupported format; not able to autodetect.").build(); } }
@Override public void filter(ContainerRequestContext requestContext) throws IOException { UriInfo uriInfo = requestContext.getUriInfo(); MultivaluedMap<String, String> params = uriInfo.getPathParameters(); String formationId = params.getFirst("formationId"); String year = params.getFirst("annee"); String semester = params.getFirst("semestre"); try { if (uePromoDao .queryBuilder() .where() .eq("formation_id", formationId) .and() .eq("year", year) .and() .eq("semester", semester) .countOf() == 0) { requestContext.abortWith(Response.status(Response.Status.NOT_FOUND).build()); } } catch (SQLException e) { e.printStackTrace(); requestContext.abortWith(Response.serverError().build()); } }
@GET public Response authorize(@Context HttpServletRequest request) { if (context == null) { throw new RuntimeException("Servlet Context has not been injected"); } if (identityManager == null) { try { identityManager = OAuthServerUtil.handleIdentityManager(context); } catch (IOException e) { log.log(Level.SEVERE, "Identity Manager setup:", e); throw new RuntimeException(e); } if (identityManager == null) { throw new RuntimeException("Identity Manager has not been created"); } } OAuthResponse response = null; try { response = OAuthServerUtil.authorizationCodeRequest(request, identityManager); } catch (OAuthSystemException e) { log.log(Level.SEVERE, "OAuth Server Authorization Processing:", e); return Response.serverError().build(); } // Check for successful processing String location = response.getLocationUri(); if (location != null && location.isEmpty() == false) { return Response.status(response.getResponseStatus()).location(URI.create(location)).build(); } else { // We have error return Response.status(response.getResponseStatus()).entity(response.getBody()).build(); } }
@Override public Response toResponse(ProcessEngineException exception) { ExceptionDto dto = ExceptionDto.fromException(exception, true); LOGGER.log(Level.WARNING, getStackTrace(exception)); return Response.serverError().entity(dto).type(MediaType.APPLICATION_JSON_TYPE).build(); }
public static Response serverErrorResponse(Throwable e, Logger logger) { if (logger != null) { logger.error(e.getMessage(), e); } return Response.serverError() .entity(Throwables.getStackTraceAsString(e)) .type(MediaType.TEXT_PLAIN_TYPE) .build(); }
/** * Retrieves the groups where the enrollment happens * * @response.representation.200.qname {http://www.example.com}groupVO * @response.representation.200.mediaType application/xml, application/json * @response.representation.200.doc The groups * @response.representation.200.example {@link * org.olat.restapi.support.vo.Examples#SAMPLE_GROUPVO} * @response.representation.401.doc The roles of the authenticated user are not sufficient * @response.representation.404.doc The course or course node not found * @param nodeId The node's id * @param httpRequest The HTTP request * @return An array of groups */ @GET @Path("{nodeId}/groups") @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response getGroups( @PathParam("courseId") Long courseId, @PathParam("nodeId") String nodeId, @Context HttpServletRequest httpRequest) { if (!isAuthor(httpRequest)) { return Response.serverError().status(Status.UNAUTHORIZED).build(); } ICourse course = CoursesWebService.loadCourse(courseId); if (course == null) { return Response.serverError().status(Status.NOT_FOUND).build(); } else if (!isAuthorEditor(course, httpRequest)) { return Response.serverError().status(Status.UNAUTHORIZED).build(); } BusinessGroupService bgs = CoreSpringFactory.getImpl(BusinessGroupService.class); CourseNode node = getParentNode(course, nodeId); ModuleConfiguration config = node.getModuleConfiguration(); String groupNames = (String) config.get(ENCourseNode.CONFIG_GROUPNAME); @SuppressWarnings("unchecked") List<Long> groupKeys = (List<Long>) config.get(ENCourseNode.CONFIG_GROUP_IDS); if (groupKeys == null && StringHelper.containsNonWhitespace(groupNames)) { groupKeys = bgs.toGroupKeys( groupNames, course.getCourseEnvironment().getCourseGroupManager().getCourseEntry()); } if (groupKeys == null || groupKeys.isEmpty()) { return Response.ok(new GroupVO[0]).build(); } List<GroupVO> voes = new ArrayList<GroupVO>(); List<BusinessGroup> groups = bgs.loadBusinessGroups(groupKeys); for (BusinessGroup group : groups) { voes.add(get(group)); } GroupVO[] voArr = new GroupVO[voes.size()]; voes.toArray(voArr); return Response.ok(voArr).build(); }