本文整理汇总了Java中com.google.api.server.spi.response.ForbiddenException类的典型用法代码示例。如果您正苦于以下问题:Java ForbiddenException类的具体用法?Java ForbiddenException怎么用?Java ForbiddenException使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
ForbiddenException类属于com.google.api.server.spi.response包,在下文中一共展示了ForbiddenException类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: get
import com.google.api.server.spi.response.ForbiddenException; //导入依赖的package包/类
/**
* Returns the {@link Article} with the corresponding ID.
*
* @param id the ID of the entity to be retrieved
* @return the entity with the corresponding ID
* @throws NotFoundException if there is no {@code Article} with the provided ID.
*/
@ApiMethod(
name = "get",
path = "article/{id}",
httpMethod = ApiMethod.HttpMethod.GET)
public Article get(@Named("id") Long id,
@Nullable @Named("timehash") Long timehash, @Nullable @Named("cert") String cert)
throws NotFoundException, UnauthorizedException, ForbiddenException {
validateRequest(timehash, cert);
Article article = ObjectifyService.ofy().load().type(Article.class).id(id).now();
if (article == null) {
throw new NotFoundException("Could not find Article with ID: " + id);
}
return article;
}
示例2: validateRequest
import com.google.api.server.spi.response.ForbiddenException; //导入依赖的package包/类
private void validateRequest(Long timehash, String cert) throws ForbiddenException {
if (timehash != null && cert != null) {
try {
QueryResultIterable<PrivateInfo> allPrivate = ObjectifyService.ofy().load().type(PrivateInfo.class).iterable();
for (PrivateInfo info : allPrivate) {
String key = doSHA1(String.format("%s;%s;%d", info.getFingerprint().toLowerCase(), info.getPackageName().toLowerCase(), timehash));
if (cert.equalsIgnoreCase(key)) {
return;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
throw new ForbiddenException("Cannot access by: " + cert + " at: " + timehash);
}
示例3: item
import com.google.api.server.spi.response.ForbiddenException; //导入依赖的package包/类
@ApiMethod(name = "alarmClock.item", httpMethod = ApiMethod.HttpMethod.GET, path="alarmClock/{alarmClockId}")
public AlarmClockBean item(@Named("alarmClockId") Long alarmClockId)
throws NotFoundException, UnauthorizedException, ForbiddenException {
try {
AlarmClockBean alarm = MyLazyClockMemcacheService.getInstance().getAlarmClock(alarmClockId);
if (alarm != null) {
return alarm;
}
alarm = AlarmClockService.getInstance().findOne(alarmClockId);
MyLazyClockMemcacheService.getInstance().addAlarmClock(alarmClockId, alarm);
return alarm;
} catch (NotFoundMyLazyClockException e) {
throw new NotFoundException(e);
}
}
示例4: delete
import com.google.api.server.spi.response.ForbiddenException; //导入依赖的package包/类
@ApiMethod(
name = "delete",
path = "{libraryKey}",
httpMethod = HttpMethod.DELETE
)
public void delete(User user, @Named("libraryKey") String key) throws ServiceException {
if(user == null) {
throw new UnauthorizedException("required authorize");
}
GasLibrary gasLibrary = LibraryService.get(key);
if(gasLibrary == null) {
throw new NotFoundException("not found library");
}
if(!gasLibrary.getAuthorKey().getName().equals(user.getEmail())) {
throw new ForbiddenException("it's not your library, you can't delete it");
}
LibraryService.delete(gasLibrary);
}
示例5: getByUrl
import com.google.api.server.spi.response.ForbiddenException; //导入依赖的package包/类
@ApiMethod(
name = "getByUrl",
path = "articleUrl",
httpMethod = ApiMethod.HttpMethod.GET)
public Article getByUrl(@Named("url") String url,
@Nullable @Named("timehash") Long timehash, @Nullable @Named("cert") String cert)
throws NotFoundException, ForbiddenException {
validateRequest(timehash, cert);
// Remove ? and #
url = url.split("\\?")[0];
url = url.split("#")[0];
String[] arr = new String[2];
arr[0] = url;
if (url.endsWith("/")) {
arr[1] = url.substring(0, url.length()-1);
} else {
arr[1] = url + "/";
}
Article article = ObjectifyService.ofy().load().type(Article.class).filter("url in", arr).first().now();
if (article == null) {
throw new NotFoundException("Could not find Article with URL: " + url);
}
return article;
}
示例6: unregister
import com.google.api.server.spi.response.ForbiddenException; //导入依赖的package包/类
/**
* Remove a registration of a user's device. When a user signs out of a client they should
* unregister. This will prevent messages from being sent to the wrong user if multiple users
* are using the same device.
*
* @param deviceId FCM token representing the device.
* @return Result containing a message about the un-registration.
* @throws BadRequestException Thrown when there is no device ID in the request.
*/
@ApiMethod(path = "unregister", httpMethod = HttpMethod.POST)
public void unregister(User user, @Named(PARAMETER_DEVICE_ID) String deviceId)
throws BadRequestException, UnauthorizedException,
com.google.api.server.spi.response.NotFoundException, ForbiddenException {
// Check to see if deviceId.
if (Strings.isNullOrEmpty(deviceId)) {
// Drop request.
throw new BadRequestException("Invalid request: Request must contain " +
PARAMETER_DEVICE_ID);
}
// Check that user making requests is non null.
if (user == null) {
throw new UnauthorizedException("Invalid credentials");
}
try {
Device device = ofy().load().type(Device.class).id(deviceId).safe();
// Check that the user trying to unregister the token is the same one that registered it.
if (!device.getUserId().equals(user.getId())) {
throw new ForbiddenException("Not authorized to unregister token");
}
DeviceStore.unregister(deviceId);
} catch (NotFoundException e) {
throw new com.google.api.server.spi.response.NotFoundException("Device ID: " + deviceId +
" not found");
}
}
示例7: testGetNoAuth
import com.google.api.server.spi.response.ForbiddenException; //导入依赖的package包/类
@Test
public void testGetNoAuth() throws Exception {
when(mockFirebaseWrapper.isUserAuthenticated()).thenReturn(false);
try {
endpoint.registrationStatus(mockServletContext, FIREBASE_TOKEN);
fail();
} catch (ForbiddenException e) {
// Expected exception.
}
}
示例8: TxResult
import com.google.api.server.spi.response.ForbiddenException; //导入依赖的package包/类
private TxResult(Throwable exception) {
if (exception instanceof NotFoundException ||
exception instanceof ForbiddenException ||
exception instanceof ConflictException) {
this.exception = exception;
} else {
throw new IllegalArgumentException("Exception not supported.");
}
}
示例9: getResult
import com.google.api.server.spi.response.ForbiddenException; //导入依赖的package包/类
private ResultType getResult() throws NotFoundException, ForbiddenException, ConflictException {
if (exception instanceof NotFoundException) {
throw (NotFoundException) exception;
}
if (exception instanceof ForbiddenException) {
throw (ForbiddenException) exception;
}
if (exception instanceof ConflictException) {
throw (ConflictException) exception;
}
return result;
}
示例10: unregisterFromConference
import com.google.api.server.spi.response.ForbiddenException; //导入依赖的package包/类
/**
* Unregister from the specified Conference.
*
* @param user An user who invokes this method, null when the user is not signed in.
* @param websafeConferenceKey The String representation of the Conference Key to unregister
* from.
* @return Boolean true when success, otherwise false.
* @throws UnauthorizedException when the user is not signed in.
* @throws NotFoundException when there is no Conference with the given conferenceId.
*/
@ApiMethod(
name = "unregisterFromConference",
path = "conference/{websafeConferenceKey}/registration",
httpMethod = HttpMethod.DELETE
)
public WrappedBoolean unregisterFromConference(final User user,
@Named("websafeConferenceKey")
final String websafeConferenceKey)
throws UnauthorizedException, NotFoundException, ForbiddenException, ConflictException {
// If not signed in, throw a 401 error.
if (user == null) {
throw new UnauthorizedException("Authorization required");
}
final String userId = getUserId(user);
TxResult<Boolean> result = ofy().transact(new Work<TxResult<Boolean>>() {
@Override
public TxResult<Boolean> run() {
Key<Conference> conferenceKey = Key.create(websafeConferenceKey);
Conference conference = ofy().load().key(conferenceKey).now();
// 404 when there is no Conference with the given conferenceId.
if (conference == null) {
return new TxResult<>(new NotFoundException(
"No Conference found with key: " + websafeConferenceKey));
}
// Un-registering from the Conference.
Profile profile = getProfileFromUser(user, userId);
if (profile.getConferenceKeysToAttend().contains(websafeConferenceKey)) {
profile.unregisterFromConference(websafeConferenceKey);
conference.giveBackSeats(1);
ofy().save().entities(profile, conference).now();
return new TxResult<>(true);
} else {
return new TxResult<>(false);
}
}
});
// NotFoundException is actually thrown here.
return new WrappedBoolean(result.getResult());
}
示例11: put
import com.google.api.server.spi.response.ForbiddenException; //导入依赖的package包/类
@ApiMethod(
name ="put",
path = "{libraryKey}",
httpMethod = HttpMethod.PUT
)
public Library put(User user, @Named("libraryKey") String key, Library library) throws ServiceException {
if(user == null) {
throw new UnauthorizedException("insert api is required authorize");
}
Member member = MemberService.get(user);
if(member == null) {
throw new ForbiddenException("Did not register your account. Please register.");
}
if(library == null) {
throw new BadRequestException("json body is required.");
}
GasLibrary gasLibrary = LibraryService.get(key);
if(gasLibrary == null) {
throw new NotFoundException("Not found library");
}
BeanUtil.copy(library, gasLibrary, new CopyOptions().include(GLM.desc, GLM.longDesc, GLM.label, GLM.sourceUrl));
LibraryService.put(gasLibrary, key);
copy(gasLibrary, library);
return library;
}
示例12: list
import com.google.api.server.spi.response.ForbiddenException; //导入依赖的package包/类
/**
* List all entities.
*
* @param cursor used for pagination to determine which page to return
* @param limit the maximum number of entries to return
* @return a response that encapsulates the result list and the next page token/cursor
*/
@ApiMethod(
name = "list",
path = "article",
httpMethod = ApiMethod.HttpMethod.GET)
public CollectionResponse<Article> list(@Named("cat") String category,
@Nullable @Named("cursor") String cursor, @Nullable @Named("limit") Integer limit,
@Nullable @Named("from") Long from, @Nullable @Named("to") Long to,
@Nullable @Named("timehash") Long timehash, @Nullable @Named("cert") String cert)
throws ForbiddenException {
validateRequest(timehash, cert);
limit = (limit == null || limit <= 0) ? DEFAULT_LIST_LIMIT : limit;
//test();
Query<Article> query = ObjectifyService.ofy().load().type(Article.class).order("-created").limit(limit);
if (category != null && !"".equals(category)) {
query = query.filter("category", category);
}
if (from != null && to != null && 0 < from && from <= to) {
query = query.filter("created >", new Date(from)).filter("created <", new Date(to));
}
if (cursor != null) {
query = query.startAt(Cursor.fromWebSafeString(cursor));
}
QueryResultIterator<Article> queryIter = query.iterator();
List<Article> articleList = new ArrayList<Article>(limit);
// TODO Use random to choose big style
Random random = new Random();
boolean isFirst = true;
while (queryIter.hasNext()) {
Article article = queryIter.next();
// To save data transfer
article.setFullContent(null);
if (isFirst || random.nextInt(8) == 0) {
article.setStyle(1);
isFirst = false;
}
articleList.add(article);
}
return CollectionResponse.<Article>builder().setItems(articleList).setNextPageToken(queryIter.getCursor().toWebSafeString()).build();
}
示例13: registrationStatus
import com.google.api.server.spi.response.ForbiddenException; //导入依赖的package包/类
@ApiMethod(path = "status", httpMethod = ApiMethod.HttpMethod.GET)
public RegistrationResult registrationStatus(ServletContext context, @Named("firebaseUserToken") String firebaseUserToken)
throws IOException, ForbiddenException, ExecutionException, InterruptedException, InternalServerErrorException {
String databaseUrl = context.getInitParameter("databaseUrl");
LOG.info("databaseUrl: " + databaseUrl);
String serviceAccountKey = context.getInitParameter("accountKey");
LOG.info("accountKey: " + serviceAccountKey);
InputStream serviceAccount = context.getResourceAsStream(serviceAccountKey);
LOG.info("serviceAccount: " + serviceAccount);
firebaseWrapper.initFirebase(databaseUrl, serviceAccount);
firebaseWrapper.authenticateFirebaseUser(firebaseUserToken);
if (!firebaseWrapper.isUserAuthenticated()) {
throw new ForbiddenException("Not authenticated");
}
boolean isRegistered = isUserRegistered(context);
final TaskCompletionSource<Boolean> isRegisteredTCS = new TaskCompletionSource<>();
final Task<Boolean> isRegisteredTCSTask = isRegisteredTCS.getTask();
// Update the user registration state in the Real-time Database.
DatabaseReference dbRef = firebaseWrapper.getDatabaseReference();
int rtdbRetries = 0;
while (rtdbRetries < RTDB_RETRY_LIMIT) {
dbRef.child("users").child(firebaseWrapper.getUserId()).setValue(isRegistered)
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(Task<Void> task) {
if (task.isSuccessful()) {
isRegisteredTCS.setResult(true);
} else {
isRegisteredTCS.setResult(false);
}
}
});
// If writing to RTDB was successful break out.
if (Tasks.await(isRegisteredTCSTask)) {
break;
}
LOG.info("Writing to RTDB has failed.");
rtdbRetries++;
}
// If retry limit was reached return false, user will have to try again if they were
// indeed registered.
if (rtdbRetries >= RTDB_RETRY_LIMIT) {
throw new InternalServerErrorException("Unable to write registration status to RTDB.");
} else {
// Return the user registration state.
return new RegistrationResult(isRegistered);
}
}
示例14: unregisterFromConference
import com.google.api.server.spi.response.ForbiddenException; //导入依赖的package包/类
/**
* Unregister from the specified Conference.
*
* @param user An user who invokes this method, null when the user is not signed in.
* @param websafeConferenceKey The String representation of the Conference Key to unregister
* from.
* @return Boolean true when success, otherwise false.
* @throws UnauthorizedException when the user is not signed in.
* @throws NotFoundException when there is no Conference with the given conferenceId.
*/
@ApiMethod(
name = "unregisterFromConference",
path = "conference/{websafeConferenceKey}/registration",
httpMethod = HttpMethod.DELETE
)
public WrappedBoolean unregisterFromConference(final User user,
@Named("websafeConferenceKey")
final String websafeConferenceKey)
throws UnauthorizedException, NotFoundException, ForbiddenException, ConflictException {
// If not signed in, throw a 401 error.
if (user == null) {
throw new UnauthorizedException("Authorization required");
}
WrappedBoolean result = ofy().transact(new Work<WrappedBoolean>() {
@Override
public WrappedBoolean run() {
Key<Conference> conferenceKey = Key.create(websafeConferenceKey);
Conference conference = ofy().load().key(conferenceKey).now();
// 404 when there is no Conference with the given conferenceId.
if (conference == null) {
return new WrappedBoolean(false,
"No Conference found with key: " + websafeConferenceKey);
}
// Un-registering from the Conference.
Profile profile = getProfileFromUser(user);
if (profile.getConferenceKeysToAttend().contains(websafeConferenceKey)) {
profile.unregisterFromConference(websafeConferenceKey);
conference.giveBackSeats(1);
ofy().save().entities(profile, conference).now();
return new WrappedBoolean(true);
} else {
return new WrappedBoolean(false, "You are not registered for this conference");
}
}
});
// if result is false
if (!result.getResult()) {
if (result.getReason().contains("No Conference found with key")) {
throw new NotFoundException (result.getReason());
}
else {
throw new ForbiddenException(result.getReason());
}
}
// NotFoundException is actually thrown here.
return new WrappedBoolean(result.getResult());
}
示例15: updateConference
import com.google.api.server.spi.response.ForbiddenException; //导入依赖的package包/类
/**
* Updates the existing Conference with the given conferenceId.
*
* @param user A user who invokes this method, null when the user is not signed in.
* @param conferenceForm A ConferenceForm object representing user's inputs.
* @param websafeConferenceKey The String representation of the Conference key.
* @return Updated Conference object.
* @throws UnauthorizedException when the user is not signed in.
* @throws NotFoundException when there is no Conference with the given conferenceId.
* @throws ForbiddenException when the user is not the owner of the Conference.
*/
@ApiMethod(
name = "updateConference",
path = "conference/{websafeConferenceKey}",
httpMethod = HttpMethod.PUT
)
public Conference updateConference(final User user, final ConferenceForm conferenceForm,
@Named("websafeConferenceKey")
final String websafeConferenceKey)
throws UnauthorizedException, NotFoundException, ForbiddenException, ConflictException {
// If not signed in, throw a 401 error.
if (user == null) {
throw new UnauthorizedException("Authorization required");
}
final String userId = getUserId(user);
// Update the conference with the conferenceForm sent from the client.
// Need a transaction because we need to safely preserve the number of allocated seats.
TxResult<Conference> result = ofy().transact(new Work<TxResult<Conference>>() {
@Override
public TxResult<Conference> run() {
// If there is no Conference with the id, throw a 404 error.
Key<Conference> conferenceKey = Key.create(websafeConferenceKey);
Conference conference = ofy().load().key(conferenceKey).now();
if (conference == null) {
return new TxResult<>(
new NotFoundException("No Conference found with the key: "
+ websafeConferenceKey));
}
// If the user is not the owner, throw a 403 error.
Profile profile = ofy().load().key(Key.create(Profile.class, userId)).now();
if (profile == null ||
!conference.getOrganizerUserId().equals(userId)) {
return new TxResult<>(
new ForbiddenException("Only the owner can update the conference."));
}
conference.updateWithConferenceForm(conferenceForm);
ofy().save().entity(conference).now();
return new TxResult<>(conference);
}
});
// NotFoundException or ForbiddenException is actually thrown here.
return result.getResult();
}