当前位置: 首页>>代码示例>>Java>>正文


Java Function类代码示例

本文整理汇总了Java中play.libs.F.Function的典型用法代码示例。如果您正苦于以下问题:Java Function类的具体用法?Java Function怎么用?Java Function使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


Function类属于play.libs.F包,在下文中一共展示了Function类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: asyncResult

import play.libs.F.Function; //导入依赖的package包/类
public static Result asyncResult() {
    return async(Akka.future(new Callable<String>() {
        @Override
        public String call() {
            return "success";
        }
    }).map(new Function<String, Result>() {
        @Override
        public Result apply(String a) {
            response().setHeader("header_test", "header_val");
            response().setCookie("cookie_test", "cookie_val");
            session("session_test", "session_val");
            flash("flash_test", "flash_val");
            return ok(a);
        };
    }));
}
 
开发者ID:vangav,项目名称:vos_backend,代码行数:18,代码来源:Application.java

示例2: findAll

import play.libs.F.Function; //导入依赖的package包/类
public static List<Todo> findAll(String accessToken) {
	WSRequestHolder req = WS.url(OAUTH_RESOURCE_SERVER_URL + "/rest/todos");
	req.setHeader("Authorization", "Bearer " + accessToken);

	Promise<List<Todo>> jsonPromise = req.get().map(new Function<WSResponse, List<Todo>>() {
		public List<Todo> apply(WSResponse response) {
			JsonNode json = response.asJson();
			ArrayNode results = (ArrayNode) json;
			List<Todo> todos = new ArrayList<Todo>();
			Iterator<JsonNode> it = results.iterator();

			while (it.hasNext()) {
				JsonNode node = it.next();
				Todo todo = new Todo();
				todo.setDescription(node.get("description").asText());
				todos.add(todo);
			}

			return todos;
		}
	});
	return jsonPromise.get(5000);
}
 
开发者ID:tcompiegne,项目名称:oauth2-client-samples,代码行数:24,代码来源:TodoService.java

示例3: findByUsername

import play.libs.F.Function; //导入依赖的package包/类
public static List<Todo> findByUsername(String accessToken, String username) {
	WSRequestHolder req = WS.url(OAUTH_RESOURCE_SERVER_URL + "/rest/todos/" + username);
	req.setHeader("Authorization", "Bearer " + accessToken);

	Promise<List<Todo>> jsonPromise = req.get().map(new Function<WSResponse, List<Todo>>() {
		public List<Todo> apply(WSResponse response) {
			JsonNode json = response.asJson();
			ArrayNode results = (ArrayNode) json;
			List<Todo> todos = new ArrayList<Todo>();
			Iterator<JsonNode> it = results.iterator();

			while (it.hasNext()) {
				JsonNode node = it.next();
				Todo todo = new Todo();
				todo.setId(node.get("id").asLong());
				todo.setDescription(node.get("description").asText());
				todo.setUsername(node.get("username").asText());
				todos.add(todo);
			}

			return todos;
		}
	});
	return jsonPromise.get(5000);
}
 
开发者ID:tcompiegne,项目名称:oauth2-client-samples,代码行数:26,代码来源:TodoService.java

示例4: index

import play.libs.F.Function; //导入依赖的package包/类
public static Promise<Result> index() {
	if (session().get("access_token") == null) {
		return Promise.pure(redirect(routes.Application.index().absoluteURL(request())));
	}

	String accessToken = session().get("access_token");
	WSRequestHolder req = WS.url(OAUTH_URL + "/userinfo");
	req.setHeader("Authorization", "Bearer " + accessToken);

	// Get the JSON Response
	Promise<Result> resultPromise = req.get().map(new Function<WSResponse, Result>() {
		public Result apply(WSResponse response) {
			if (200 == response.getStatus()) {
				// get the user info
				String username = response.asJson().get("username").textValue();
				session().put("username", username);

				return redirect(routes.Application.index().absoluteURL(request()));
			}

			// go back to authentication
			return redirect(OAuthUtils.oAuthAuthorizeUrl());
		}
	});
	return resultPromise;
}
 
开发者ID:tcompiegne,项目名称:oauth2-client-samples,代码行数:27,代码来源:UserInfo.java

示例5: getJsonFrom

import play.libs.F.Function; //导入依赖的package包/类
protected static JsonNode getJsonFrom(String cookie, String url) {
Logger.info("Getting "+url);
while(true) {
    try {
	Promise<JsonNode> jsonPromise = WS.url(url).setRequestTimeout(timeout).setHeader("Cookie", cookie).get().map(
		new Function<WSResponse, JsonNode>() {
		    public JsonNode apply(WSResponse response) {
			JsonNode json = response.asJson();
			return json;
		    }
		}
		);
	return jsonPromise.get(timeout);
    } catch( Exception e ) {
	Logger.error("Exception while talking to W3ACT - sleeping for 15 seconds before retrying.",e);
	try {
	    Thread.sleep(15*1000);
	} catch (InterruptedException e1) {
	    Logger.error("Thread sleep was interrupted.",e);
	}
    }
}
   }
 
开发者ID:ukwa,项目名称:ukwa,代码行数:24,代码来源:W3ACTCache.java

示例6: inSession

import play.libs.F.Function; //导入依赖的package包/类
/**
 * Perform the given function in a session, then close it after saving any
 * pending changes.
 *
 * @param session the JCR session to use
 * @param func a function to perform in the session
 * @throws RuntimeException wraps any exception that may have been thrown
 * @returns return value of the function
 */
protected <R> R inSession(Session session, Function<Session, R> func) {
  try {
    R result = func.apply(session);
    if (session.isLive() && session.hasPendingChanges()) {
      session.save();
    }
    return result;
  } catch (Throwable e) {
    throw new RuntimeException(e);
  } finally {
    if (session.isLive()) {
      session.logout();
    }
  }
}
 
开发者ID:uq-eresearch,项目名称:aorra,代码行数:25,代码来源:JcrSessionFactory.java

示例7: getAdminUser

import play.libs.F.Function; //导入依赖的package包/类
public String getAdminUser(JcrSessionFactory sessionFactory) {
  return sessionFactory.inSession(new Function<Session,String>() {
    @Override
    public String apply(Session session) throws RepositoryException {
      // Create new user
      final String userId;
      UserDAO dao = new UserDAO(session, jcrom());
      User user = new User();
      user.setEmail("[email protected]");
      user.setName("Test User");
      user = dao.create(user);
      String token = user.createVerificationToken();
      user.checkVerificationToken(token);
      dao.setPassword(user, "password");
      userId = user.getJackrabbitUserId();
      final GroupManager gm = new GroupManager(session);
      Admin.getInstance(session).getGroup().addMember(gm.create("testAdmin"));
      gm.addMember("testAdmin", userId);
      return userId;
    }
  });
}
 
开发者ID:uq-eresearch,项目名称:aorra,代码行数:23,代码来源:FileStoreTest.java

示例8: canGetInstance

import play.libs.F.Function; //导入依赖的package包/类
@Test
public void canGetInstance() {
  running(fakeAorraApp(), new Runnable() {
    @Override
    public void run() {
      JcrSessionFactory sessionFactory = GuiceInjectionPlugin
          .getInjector(Play.application())
          .getInstance(JcrSessionFactory.class);
      sessionFactory.inSession(new Function<Session,Admin>() {
        @Override
        public Admin apply(Session session) throws RepositoryException {
          Admin admin = Admin.getInstance(session);
          assertThat(admin).isNotNull();
          assertThat(admin.getGroup()).isNotNull();
          try {
            assertThat(admin.getGroup().getID()).isEqualTo(Admin.GROUP_ID);
          } catch (RepositoryException e) {
            throw new RuntimeException(e);
          }
          return admin;
        }
      });
    }
  });
}
 
开发者ID:uq-eresearch,项目名称:aorra,代码行数:26,代码来源:AdminTest.java

示例9: onlyOneTrueAdminGroupExists

import play.libs.F.Function; //导入依赖的package包/类
@Test
public void onlyOneTrueAdminGroupExists() {
  running(fakeAorraApp(), new Runnable() {
    @Override
    public void run() {
      JcrSessionFactory sessionFactory = GuiceInjectionPlugin
          .getInjector(Play.application())
          .getInstance(JcrSessionFactory.class);
      sessionFactory.inSession(new Function<Session,Session>() {
        @Override
        public Session apply(Session session) throws RepositoryException {
          Admin admin1 = Admin.getInstance(session);
          Admin admin2 = Admin.getInstance(session);
          assertThat(admin1.getGroup().getID())
            .isEqualTo(admin2.getGroup().getID());
          return session;
        }
      });
    }
  });
}
 
开发者ID:uq-eresearch,项目名称:aorra,代码行数:22,代码来源:AdminTest.java

示例10: getAsyncResult

import play.libs.F.Function; //导入依赖的package包/类
private static Function<JsonNode, Promise<Result>> getAsyncResult(final Request request, final Response response, final String cacheLen) {
	return new Function<JsonNode, Promise<Result>>() {
		@Override
		public Promise<Result> apply(final JsonNode node) throws Throwable {
			return Promise.wrap(akka.dispatch.Futures.future((new Callable<Result>() {
				@Override
				public Result call() throws Exception {
					Result result = Utils.handleDefaultGetHeaders(request, response, String.valueOf(node.hashCode()), cacheLen);
					if (result != null) {
						return result;
					}
					return Results.ok(node).as("application/json");
				}
				
			}), Akka.system().dispatcher()));
		}
	};
}
 
开发者ID:NationStates,项目名称:NationStatesPlusPlus,代码行数:19,代码来源:RMBController.java

示例11: delete

import play.libs.F.Function; //导入依赖的package包/类
public static String delete(String accessToken, String username, Long id) {
	WSRequestHolder req = WS.url(OAUTH_RESOURCE_SERVER_URL + "/rest/todos/" + id + "/delete");
	req.setHeader("Authorization", "Bearer " + accessToken);

	Promise<String> jsonPromise = req.post("").map(new Function<WSResponse, String>() {
		public String apply(WSResponse response) {
			JsonNode json = response.asJson();
			return json.asText();
		}
	});

	return jsonPromise.get(5000);

}
 
开发者ID:tcompiegne,项目名称:oauth2-client-samples,代码行数:15,代码来源:TodoService.java

示例12: callback

import play.libs.F.Function; //导入依赖的package包/类
public static Promise<Result> callback() {
	// get the authorization code
	String authorizationCode = request().getQueryString("code");
	
	// call OAuth Server with response code to get the access token
	WSRequestHolder req = WS.url(OAUTH_URL+"/oauth/token").setAuth(OAUTH_CLIENT_ID, OAUTH_CLIENT_SECRET, WSAuthScheme.BASIC);
	req.setQueryParameter("grant_type", "authorization_code");
	req.setQueryParameter("code", authorizationCode);
	req.setQueryParameter("redirect_uri", OAUTH_REDIRECT_URI);
	
	// Get the JSON Response
	Promise<Result> resultPromise = req.post("content").map(
	        new Function<WSResponse, Result>() {
	            public Result apply(WSResponse response) {
	            	if (200 == response.getStatus()) {
	            		// get the access token
	            		String accessToken = response.asJson().get("access_token").textValue();
	            		session().put("access_token", accessToken);
	            		// get the user information
	            		return redirect(routes.UserInfo.index().absoluteURL(request()));
	            	}
	            		
            		// go back to authentication
	                return redirect(OAuthUtils.oAuthAuthorizeUrl());
	            }
	        }
	);
	
	return resultPromise; 
}
 
开发者ID:tcompiegne,项目名称:oauth2-client-samples,代码行数:31,代码来源:OAuth.java

示例13: getPhotographImage

import play.libs.F.Function; //导入依赖的package包/类
public static Promise<Result> getPhotographImage(final String photographId) {
	try {
		final PhotographDocument photographDocument = PhotostashDatabase.INSTANCE.getPhotograph(photographId);
		if (photographDocument == null) {
			return Promise.promise(new Function0<Result>() {
				@Override
				public Status apply() throws Throwable {
					return badRequest(Json.newObject().put("message", photographId + " not found."));
				}
			});
		} else {
			return Promise.wrap(ask(Shoebox.INSTANCE.getPhotographRouter(), new PhotographRequestMessage(photographDocument), PHOTOGRAPH_REQUEST_TIMEOUT)).map(new Function<Object, Result>() {
				public Result apply(Object response) {
					if (response instanceof PhotographResponseMessage) {
						PhotographResponseMessage photographResponseMessage = (PhotographResponseMessage) response;
						return ok(photographResponseMessage.getPhotograph()).as(photographResponseMessage.getMimeType());
					} else {
						return internalServerError(Json.newObject().put("message", response.toString()));
					}
				}
			});
		}
	} catch (final DatabaseException e) {
		return Promise.promise(new Function0<Result>() {
			@Override
			public Status apply() throws Throwable {
				return internalServerError(Json.newObject().put("message", e.getMessage()));
			}
		});

	}
}
 
开发者ID:corbantek,项目名称:play-photostash,代码行数:33,代码来源:PhotographController.java

示例14: getPhotographResizeImage

import play.libs.F.Function; //导入依赖的package包/类
public static Promise<Result> getPhotographResizeImage(final String photographId, final Integer squareSize) {
	try {
		final PhotographDocument photographDocument = PhotostashDatabase.INSTANCE.getPhotograph(photographId);
		if (photographDocument == null) {
			return Promise.promise(new Function0<Result>() {
				@Override
				public Status apply() throws Throwable {
					return badRequest(Json.newObject().put("message", photographId + " not found."));
				}
			});
		} else {
			if (squareSize == null) {
				return getPhotographImage(photographId);
			} else {
				return Promise.wrap(ask(Shoebox.INSTANCE.getPhotographRouter(), new PhotographResizeRequestMessage(photographDocument, squareSize), PHOTOGRAPH_REQUEST_TIMEOUT)).map(new Function<Object, Result>() {
					public Result apply(Object response) {
						if (response instanceof PhotographResponseMessage) {
							PhotographResponseMessage photographResponseMessage = (PhotographResponseMessage) response;
							return ok(photographResponseMessage.getPhotograph()).as(photographResponseMessage.getMimeType());
						} else {
							return internalServerError(Json.newObject().put("message", response.toString()));
						}
					}
				});
			}
		}
	} catch (final DatabaseException e) {
		return Promise.promise(new Function0<Result>() {
			@Override
			public Status apply() throws Throwable {
				return internalServerError(Json.newObject().put("message", e.getMessage()));
			}
		});

	}
}
 
开发者ID:corbantek,项目名称:play-photostash,代码行数:37,代码来源:PhotographController.java

示例15: healthcheck

import play.libs.F.Function; //导入依赖的package包/类
public Promise<Result> healthcheck() {
	return Promise.wrap(ask(healthCheckActor, new HealthChecksRequest(), 60000)).map(
		new Function<Object, Result>() {
			public Result apply(Object response) {
				HealthCheckResponses responses = (HealthCheckResponses) response;
				ViewModel vm = new ViewModel(responses.getResults());
				boolean return500OnError = true;
				if(config.getString(return500OnErrorKey) != null) return500OnError = config.getBoolean(return500OnErrorKey);
				if(return500OnError && !vm.isHealthy()) return internalServerError(views.html.healthcheck.render(vm));
				else return ok(views.html.healthcheck.render(vm));
			}
	});
}
 
开发者ID:chanan,项目名称:PlayGuiceStatsD,代码行数:14,代码来源:HealthCheckController.java


注:本文中的play.libs.F.Function类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。