本文整理汇总了Java中i5.las2peer.security.UserAgent类的典型用法代码示例。如果您正苦于以下问题:Java UserAgent类的具体用法?Java UserAgent怎么用?Java UserAgent使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
UserAgent类属于i5.las2peer.security包,在下文中一共展示了UserAgent类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: getActiveUserInfo
import i5.las2peer.security.UserAgent; //导入依赖的package包/类
private JSONObject getActiveUserInfo() throws ParseException {
if(this.getActiveAgent() instanceof UserAgent){
UserAgent me = (UserAgent) this.getActiveAgent();
JSONObject o;
if(me.getUserData() != null){
System.err.println(me.getUserData());
o = (JSONObject) JSONValue.parseWithException((String) me.getUserData());
} else {
o = new JSONObject();
if(getActiveNode().getAnonymous().getId() == getActiveAgent().getId()){
o.put("sub","anonymous");
} else {
String md5ide = new String(""+me.getId());
o.put("sub", md5ide);
}
}
return o;
} else {
return new JSONObject();
}
}
示例2: getDBLogin
import i5.las2peer.security.UserAgent; //导入依赖的package包/类
/**
* Creates automatic user name and password from las2peer login data (private key is hashed)
* @return name and password for DB login
* @throws Exception
*/
private StringTuple getDBLogin() throws Exception
{
Long userID=this.getContext().getMainAgent().getId();
String name=((UserAgent)(this.getContext().getLocalNode().getAgent(userID))).getLoginName();
String key=Base64.encodeBase64String(this.getContext().getMainAgent().getPrivateKey().getEncoded());
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(key.getBytes("UTF-8"));
byte[] digest = md.digest();
String pass=Base64.encodeBase64String(digest);
name=name.replace(" ", "_");
return new StringTuple(name,pass);
}
示例3: getAuthorInformation
import i5.las2peer.security.UserAgent; //导入依赖的package包/类
/**
* Method to create a JSONObject containing information about the user signed in
* @return authorInformation
*/
private JSONObject getAuthorInformation(){
JSONObject authorInformation = null;
try {
authorInformation = getActiveUserInfo();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
authorInformation.put(NAME.toString(), (String)((UserAgent) getActiveAgent()).getLoginName());
//authorInformation.put("sub", authorInformation.get("sub"));
authorInformation.put(URI.toString(), "");
return authorInformation;
}
示例4: validateLogin
import i5.las2peer.security.UserAgent; //导入依赖的package包/类
@GET
@Path("/validation")
@Produces(MediaType.TEXT_PLAIN)
@ApiResponses(value = { @ApiResponse(code = 200, message = "Validation Confirmation")})
@ApiOperation(value = "User Validation",
notes = "Simple function to validate a user login.")
public HttpResponse validateLogin() {
String returnString = "";
returnString += "You are " + ((UserAgent) getActiveAgent()).getLoginName() + " and your login is valid!";
return new HttpResponse(returnString, 200);
}
示例5: storeGraph
import i5.las2peer.security.UserAgent; //导入依赖的package包/类
/**
* Stores big graphs step by step.
*
* @param nameStr
* The name for the graph.
* @param contentStr
* The graph input.
* @return XML containing information about the stored file.
*/
@POST
@Path("storegraph")
@Produces(MediaType.TEXT_XML)
@Consumes(MediaType.TEXT_PLAIN)
@ApiResponses(value = { @ApiResponse(code = 200, message = "Success"),
@ApiResponse(code = 401, message = "Unauthorized") })
@ApiOperation(value = "User validation", notes = "Stores a graph step by step.")
public Response storeGraph(@DefaultValue("unnamed") @QueryParam("name") String nameStr, String contentStr) {
String username = ((UserAgent) Context.getCurrent().getMainAgent()).getLoginName();
File graphDir = new File("tmp" + File.separator + username);
if (!graphDir.exists()) {
graphDir.mkdirs();
}
File graphFile = new File(graphDir + File.separator + nameStr + ".txt");
try (FileWriter fileWriter = new FileWriter(graphFile, true);
BufferedWriter bufferWritter = new BufferedWriter(fileWriter);) {
if (!graphFile.exists()) {
graphFile.createNewFile();
}
bufferWritter.write(contentStr);
bufferWritter.newLine();
} catch (Exception e) {
requestHandler.log(Level.WARNING, "user: " + username, e);
return requestHandler.writeError(Error.INTERNAL, "Internal system error.");
}
return Response.ok("<?xml version=\"1.0\" encoding=\"UTF-16\"?>" + "<File>" + "<Name>" + graphFile.getName()
+ "</Name>" + "<Size>" + graphFile.length() + "</Size>" + "<Message>" + "File appned" + "</Message>"
+ "</File>").build();
}
示例6: processStoredGraph
import i5.las2peer.security.UserAgent; //导入依赖的package包/类
/**
* Process the stored graph which was stored by storeGraph api.
*
* @param nameStr
* The name for the stored graph.
* @param creationTypeStr
* The creation type the graph was created by.
* @param graphInputFormatStr
* The name of the graph input format.
* @param doMakeUndirectedStr
* Optional query parameter. Defines whether directed edges
* shall be turned into undirected edges (TRUE) or not.
* @param startDateStr
* Optional query parameter. For big graphs start date is the
* date from which the file will start parse.
* @param endDateStr
* Optional query parameter. For big graphs end date is the
* date till which the file will parse.
* @param indexPathStr
* Optional query parameter. Set index directory.
* @param filePathStr
* Optional query parameter. For testing purpose, file
* location of local file can be given.
* @return A graph id xml. Or an error xml.
*/
@POST
@Path("processgraph")
@Produces(MediaType.TEXT_XML)
@Consumes(MediaType.TEXT_PLAIN)
@ApiResponses(value = { @ApiResponse(code = 200, message = "Success"),
@ApiResponse(code = 401, message = "Unauthorized") })
@ApiOperation(value = "User validation", notes = "Process the stored graph.")
public Response processStoredGraph(@DefaultValue("unnamed") @QueryParam("name") String nameStr,
@DefaultValue("UNDEFINED") @QueryParam("creationType") String creationTypeStr,
@DefaultValue("GRAPH_ML") @QueryParam("inputFormat") String graphInputFormatStr,
@DefaultValue("FALSE") @QueryParam("doMakeUndirected") String doMakeUndirectedStr,
@DefaultValue("2004-01-01") @QueryParam("startDate") String startDateStr,
@DefaultValue("2004-01-20") @QueryParam("endDate") String endDateStr,
@DefaultValue("indexes") @QueryParam("indexPath") String indexPathStr,
@DefaultValue("ocd/test/input/stackexAcademia.xml") @QueryParam("filePath") String filePathStr) {
String username = ((UserAgent) Context.getCurrent().getMainAgent()).getLoginName();
File graphDir = new File("tmp" + File.separator + username);
File graphFile = new File(graphDir + File.separator + nameStr + ".txt");
StringBuffer contentStr = new StringBuffer();
if (!graphFile.exists()) {
return requestHandler.writeError(Error.INTERNAL, "Graph Does not exists.");
}
try (FileReader fileWriter = new FileReader(graphFile);
BufferedReader bufferedReader = new BufferedReader(fileWriter);) {
String line;
while ((line = bufferedReader.readLine()) != null) {
contentStr.append(line);
contentStr.append("\n");
}
} catch (Exception e) {
requestHandler.log(Level.WARNING, "user: " + username, e);
return requestHandler.writeError(Error.INTERNAL, "Internal system error.");
}
graphFile.delete();
return createGraph(nameStr, creationTypeStr, graphInputFormatStr, doMakeUndirectedStr, startDateStr,
endDateStr, indexPathStr, filePathStr, contentStr.toString());
}
示例7: getSimulation
import i5.las2peer.security.UserAgent; //导入依赖的package包/类
/**
* Gets the results of a performed simulation series on a network
*
* @return HttpResponse with the returnString
*/
@GET
@Path("/simulation/{seriesId}")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "GET SIMULATION", notes = "Gets the results of a performed simulation")
@ApiResponses(value = {
@ApiResponse(code = HttpURLConnection.HTTP_OK, message = "REPLACE THIS WITH YOUR OK MESSAGE"),
@ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized") })
public Response getSimulation(@PathParam("seriesId") long seriesId) {
String username = ((UserAgent) Context.getCurrent().getMainAgent()).getLoginName();
SimulationSeries series = null;
try {
series = entityHandler.getSimulationSeries(seriesId);
if (series == null)
return Response.status(Status.BAD_REQUEST).entity("no simulation with id " + seriesId + " found")
.build();
if (!series.isEvaluated()) {
series.evaluate();
}
} catch (Exception e) {
logger.log(Level.WARNING, "user: " + username, e);
e.printStackTrace();
return Response.status(Status.INTERNAL_SERVER_ERROR).entity("internal error").build();
}
return Response.ok().entity(series).build();
}
示例8: getGraphById
import i5.las2peer.security.UserAgent; //导入依赖的package包/类
/**
* Transforms the stored CustomGraph into a HashMap. The HashMap include the
* graph as adjacency list.
*
* This method is intended to be used by other las2peer services for remote
* method invocation. It returns only default types and classes.
*
*
* @param graphId
* Id of the requested stored graph
* @return HashMap
*
*/
public Map<String, Object> getGraphById(long graphId) {
String username = ((UserAgent) Context.getCurrent().getMainAgent()).getLoginName();
CustomGraph graph;
try {
graph = entityHandler.getGraph(username, graphId);
} catch (Exception e) {
e.printStackTrace();
return null;
}
Integer nodeCount = graph.nodeCount();
Integer edgeCount = graph.edgeCount();
Boolean directed = graph.isDirected();
Boolean weighted = graph.isWeighted();
String name = graph.getName();
InvocationHandler invocationHandler = new InvocationHandler();
List<List<Integer>> adjList = invocationHandler.getAdjList(graph);
Map<String, Object> graphData = new HashMap<String, Object>();
graphData.put("nodes", nodeCount);
graphData.put("edges", edgeCount);
graphData.put("directed", directed);
graphData.put("weighted", weighted);
graphData.put("name", name);
graphData.put("graph", adjList);
logger.log(Level.INFO, "RMI requested a graph: " + graphId);
return graphData;
}
示例9: getGraphIds
import i5.las2peer.security.UserAgent; //导入依赖的package包/类
/**
* Get a List of all graph indices of a user
*
* @param graphId
* Id of the requested stored graph
* @return HashMap
*
*/
public List<Long> getGraphIds() throws AgentNotKnownException {
String username = ((UserAgent) Context.getCurrent().getMainAgent()).getLoginName();
List<Long> graphIdList = new ArrayList<Long>();
List<CustomGraph> graphList = entityHandler.getGraphs(username);
for (int i = 0, si = graphList.size(); i < si; i++) {
graphIdList.add(graphList.get(i).getId());
}
logger.log(Level.INFO, "RMI requested graph Ids");
return graphIdList;
}
示例10: getCoverById
import i5.las2peer.security.UserAgent; //导入依赖的package包/类
/**
* Get the community lists representing the community structure.
*
* This method is intended to be used by other las2peer services for remote
* method invocation. It returns only default types and classes.
*
* @param graphId
* Index of the requested graph
* @param coverId
* Index of the requested community cover
*
* @return HashMap including the community members lists. The outer list has
* an entry for every community of the cover. The inner list
* contains the indices of the member nodes.
*
*/
public Map<String, Object> getCoverById(long graphId, long coverId) {
String username = ((UserAgent) Context.getCurrent().getMainAgent()).getLoginName();
Cover cover;
try {
cover = entityHandler.getCover(username, graphId, coverId);
} catch (Exception e) {
e.printStackTrace();
return null;
}
int communityCount = cover.communityCount();
String algorithm = cover.getCreationMethod().getType().toString();
InvocationHandler invocationHandler = new InvocationHandler();
List<List<Integer>> communityMemberList = invocationHandler.getCommunityMemberList(cover);
Map<String, Object> coverData = new HashMap<String, Object>();
coverData.put("size", communityCount);
coverData.put("algorithm", algorithm);
coverData.put("graphId", graphId);
coverData.put("coverId", coverId);
coverData.put("cover", communityMemberList);
return coverData;
}
示例11: getCoverIdsByGraphId
import i5.las2peer.security.UserAgent; //导入依赖的package包/类
/**
* List of cover indices that are available for a given graph id
*
* This method is intended to be used by other las2peer services for remote
* method invocation. It returns only default types and classes.
*
* @param graphId
* Index of the requested graph
*
* @return list containing cover indices.
*
*/
public List<Long> getCoverIdsByGraphId(long graphId) {
String username = ((UserAgent) Context.getCurrent().getMainAgent()).getLoginName();
List<Cover> covers = entityHandler.getCovers(username, graphId);
int size = covers.size();
List<Long> coverIds = new ArrayList<>(size);
for (int i = 0; i < size; i++) {
coverIds.add(covers.get(i).getId());
}
return coverIds;
}
示例12: startServer
import i5.las2peer.security.UserAgent; //导入依赖的package包/类
@BeforeClass
public static void startServer() throws Exception {
// init agents
UserAgent eve = MockAgentFactory.getEve();
eve.unlockPrivateKey("evespass");
UserAgent adam = MockAgentFactory.getAdam();
adam.unlockPrivateKey("adamspass");
adam.setLoginName("adam");
UserAgent abel = MockAgentFactory.getAbel();
abel.unlockPrivateKey("abelspass");
GroupAgent group1 = MockAgentFactory.getGroup1();
group1.unlockPrivateKey(adam);
// start Node
node = LocalNode.newNode();
node.storeAgent(eve);
node.storeAgent(adam);
node.storeAgent(abel);
node.storeAgent(group1);
node.launch();
ServiceAgent testService1 = ServiceAgent.createServiceAgent(ServiceNameVersion.fromString(testServiceClass1),
"a pass");
ServiceAgent testService2 = ServiceAgent.createServiceAgent(ServiceNameVersion.fromString(testServiceClass2),
"a pass");
ServiceAgent testService3 = ServiceAgent.createServiceAgent(ServiceNameVersion.fromString(testServiceClass3),
"a pass");
ServiceAgent testService4 = ServiceAgent.createServiceAgent(ServiceNameVersion.fromString(testServiceClass4),
"a pass");
ServiceAgent testService5 = ServiceAgent.createServiceAgent(ServiceNameVersion.fromString(testServiceClass5),
"a pass");
ServiceAgent testService6 = ServiceAgent.createServiceAgent(ServiceNameVersion.fromString(testServiceClass6),
"a pass");
testService1.unlockPrivateKey("a pass");
testService2.unlockPrivateKey("a pass");
testService3.unlockPrivateKey("a pass");
testService4.unlockPrivateKey("a pass");
testService5.unlockPrivateKey("a pass");
testService6.unlockPrivateKey("a pass");
node.registerReceiver(testService1);
node.registerReceiver(testService2);
node.registerReceiver(testService3);
node.registerReceiver(testService4);
node.registerReceiver(testService5);
node.registerReceiver(testService6);
// start connector
connector = new WebConnector(true, HTTP_PORT, false, 1000);
connector.setCrossOriginResourceDomain("*");
connector.setCrossOriginResourceSharing(true);
logStream = new ByteArrayOutputStream();
connector.setLogStream(new PrintStream(logStream));
connector.start(node);
testAgent = adam;
}
示例13: startServer
import i5.las2peer.security.UserAgent; //导入依赖的package包/类
@BeforeClass
public static void startServer() throws Exception {
// init agents
UserAgent eve = MockAgentFactory.getEve();
eve.unlockPrivateKey("evespass");
UserAgent adam = MockAgentFactory.getAdam();
adam.unlockPrivateKey("adamspass");
UserAgent abel = MockAgentFactory.getAbel();
abel.unlockPrivateKey("abelspass");
GroupAgent group1 = MockAgentFactory.getGroup1();
group1.unlockPrivateKey(adam);
// start Node
node = LocalNode.newNode();
node.storeAgent(eve);
node.storeAgent(adam);
node.storeAgent(abel);
node.storeAgent(group1);
node.launch();
ServiceAgent testService1 = ServiceAgent.createServiceAgent(ServiceNameVersion.fromString(testServiceClass1),
"a pass");
ServiceAgent testService2 = ServiceAgent.createServiceAgent(ServiceNameVersion.fromString(testServiceClass2),
"a pass");
ServiceAgent testService3 = ServiceAgent.createServiceAgent(ServiceNameVersion.fromString(testServiceClass3),
"a pass");
ServiceAgent testService4 = ServiceAgent.createServiceAgent(ServiceNameVersion.fromString(testServiceClass4),
"a pass");
ServiceAgent testService5 = ServiceAgent.createServiceAgent(ServiceNameVersion.fromString(testServiceClass5),
"a pass");
ServiceAgent testService6 = ServiceAgent.createServiceAgent(ServiceNameVersion.fromString(testServiceClass6),
"a pass");
testService1.unlockPrivateKey("a pass");
testService2.unlockPrivateKey("a pass");
testService3.unlockPrivateKey("a pass");
testService4.unlockPrivateKey("a pass");
testService5.unlockPrivateKey("a pass");
testService6.unlockPrivateKey("a pass");
node.registerReceiver(testService1);
node.registerReceiver(testService2);
node.registerReceiver(testService3);
node.registerReceiver(testService4);
node.registerReceiver(testService5);
node.registerReceiver(testService6); // should not throw an error
// start connector
logStream = new ByteArrayOutputStream();
connector = new WebConnector(true, HTTP_PORT, false, 1000);
connector.setLogStream(new PrintStream(logStream));
connector.start(node);
// eve is the anonymous agent!
testAgent = MockAgentFactory.getAdam();
}
示例14: getUserName
import i5.las2peer.security.UserAgent; //导入依赖的package包/类
public static String getUserName() {
return ((UserAgent) Context.getCurrent().getMainAgent()).getLoginName();
}
示例15: registerUserAtFirstLogin
import i5.las2peer.security.UserAgent; //导入依赖的package包/类
private void registerUserAtFirstLogin() throws Exception {
UserAgent agent = (UserAgent) getActiveAgent();
if (agent.getEmail() == null) agent.setEmail("[email protected]");
String profileImage = "https://api.learning-layers.eu/profile.png";
String givenName = null;
String familyName = null;
//TODO how to check if the user is anonymous?
if (agent.getLoginName().equals("anonymous")) {
agent.setEmail("[email protected]");
} else if (agent.getUserData() != null) {
JsonNode userDataJson = mapper.readTree(agent.getUserData().toString());
JsonNode pictureJson = userDataJson.get("picture");
String agentPicture;
if (pictureJson == null)
agentPicture = profileImage;
else
agentPicture = pictureJson.textValue();
if (agentPicture != null && !agentPicture.isEmpty())
profileImage = agentPicture;
String givenNameData = userDataJson.get("given_name").textValue();
if (givenNameData != null && !givenNameData.isEmpty())
givenName = givenNameData;
String familyNameData = userDataJson.get("family_name").textValue();
if (familyNameData != null && !familyNameData.isEmpty())
familyName = familyNameData;
}
DALFacade dalFacade = null;
try {
dalFacade = getDBConnection();
Integer userIdByLAS2PeerId = dalFacade.getUserIdByLAS2PeerId(agent.getId());
if (userIdByLAS2PeerId == null) {
// create user
User.Builder userBuilder = User.geBuilder(agent.getEmail());
if (givenName != null)
userBuilder = userBuilder.firstName(givenName);
if (familyName != null)
userBuilder = userBuilder.lastName(familyName);
User user = userBuilder.admin(false).las2peerId(agent.getId()).userName(agent.getLoginName()).profileImage(profileImage)
.emailLeadSubscription(true).emailFollowSubscription(true).build();
int userId = dalFacade.createUser(user).getId();
this.getNotificationDispatcher().dispatchNotification(user.getCreationDate(), Activity.ActivityAction.CREATE, NodeObserver.Event.SERVICE_CUSTOM_MESSAGE_55,
userId, Activity.DataType.USER, userId);
dalFacade.addUserToRole(userId, "SystemAdmin", null);
} else {
// update lastLoginDate
dalFacade.updateLastLoginDate(userIdByLAS2PeerId);
}
} catch (Exception ex) {
ExceptionHandler.getInstance().convertAndThrowException(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, Localization.getInstance().getResourceBundle().getString("error.first_login"));
logger.warning(ex.getMessage());
} finally {
closeDBConnection(dalFacade);
}
}