下面列出了javax.servlet.http.HttpServletRequest#getLocalAddr() 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private void recordAudit(HttpServletRequest httpRequest, String whenISO9601, String who) {
final String fromHost = httpRequest.getRemoteHost();
final String fromAddress = httpRequest.getRemoteAddr();
final String whatRequest = httpRequest.getMethod();
final String whatURL = Servlets.getRequestURL(httpRequest);
final String whatAddrs = httpRequest.getLocalAddr();
final String whatUrlPath = httpRequest.getRequestURL().toString();//url path without query string
if (!isOperationExcludedFromAudit(whatRequest, whatUrlPath.toLowerCase(), null)) {
audit(who, fromAddress, whatRequest, fromHost, whatURL, whatAddrs, whenISO9601);
} else {
if(LOG.isDebugEnabled()) {
LOG.debug(" Skipping Audit for {} ", whatURL);
}
}
}
@Override
public void createForPrivateCalls(String page, String action, String log, HttpServletRequest request) {
// Only log if cerberus_log_publiccalls parameter is equal to Y.
String myUser = "";
String remoteIP = "";
String localIP = "";
if (request != null) {
remoteIP = request.getRemoteAddr();
if (request.getHeader("x-forwarded-for") != null) {
remoteIP = request.getHeader("x-forwarded-for");
}
if (!(request.getUserPrincipal() == null)) {
myUser = ParameterParserUtil.parseStringParam(request.getUserPrincipal().getName(), "");
}
localIP = request.getLocalAddr();
}
this.create(factoryLogEvent.create(0, 0, myUser, null, page, action, log, remoteIP, localIP));
}
private void accept(HttpServletRequest req, HttpServletResponse resp) {
try {
String path = "http://" + req.getLocalAddr() + ":" + req.getLocalPort() + req.getContextPath();
InputStream is = getClass().getResourceAsStream(
"/com/ramussoft/jnlp/ramus-local.jnlp");
ByteArrayOutputStream out = new ByteArrayOutputStream();
int r;
while ((r = is.read()) >= 0)
out.write(r);
String string = MessageFormat.format(new String(out.toByteArray(),
"UTF8"), path);
resp.setContentType("application/x-java-jnlp-file");
OutputStream o = resp.getOutputStream();
o.write(string.getBytes("UTF8"));
o.close();
} catch (IOException e) {
e.printStackTrace();
}
}
@POST
@Path( "stopMonitoring")
@Produces( MediaType.APPLICATION_JSON)
public Response stopMonitoring(
@Context HttpServletRequest request,
BasePojo basePojo ) {
final String caller = getCaller(request, basePojo, false);
ThreadsPerCaller.registerThread(caller);
try {
SessionData sd = getSessionData(request, basePojo);
RestSystemMonitor restSystemMonitor = sd.getSystemMonitor();
String agent = request.getLocalAddr() + ":" + request.getLocalPort();
restSystemMonitor.stopMonitoring(agent);
} catch (Exception e) {
return Response.serverError().entity(new ErrorPojo(e)).build();
} finally {
ThreadsPerCaller.unregisterThread();
}
return Response.ok("{\"status\":\"monitoring stopped.\"}").build();
}
private void accept(HttpServletRequest req, HttpServletResponse resp) {
try {
String localAddr = req.getLocalAddr();
Properties properties = EngineFactory.getPropeties();
if (properties.getProperty("hostname") != null) {
localAddr = properties.getProperty("hostname");
}
String path = "http://" + localAddr + ":" + req.getLocalPort() + req.getContextPath();
InputStream is = getClass().getResourceAsStream(
"/com/ramussoft/jnlp/ramus-client.jnlp");
ByteArrayOutputStream out = new ByteArrayOutputStream();
int r;
while ((r = is.read()) >= 0)
out.write(r);
String string = MessageFormat.format(new String(out.toByteArray(),
"UTF8"), path);
resp.setContentType("application/x-java-jnlp-file");
OutputStream o = resp.getOutputStream();
o.write(string.getBytes("UTF8"));
o.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private void accept(HttpServletRequest req, HttpServletResponse resp) {
try {
String localAddr = req.getLocalAddr();
Properties properties = EngineFactory.getPropeties();
if (properties.getProperty("hostname") != null) {
localAddr = properties.getProperty("hostname");
}
String path = "http://" + localAddr + ":" + req.getLocalPort()
+ req.getContextPath();
InputStream is = getClass().getResourceAsStream(
"/com/ramussoft/jnlp/season-internet-client.jnlp");
ByteArrayOutputStream out = new ByteArrayOutputStream();
int r;
while ((r = is.read()) >= 0)
out.write(r);
String string = MessageFormat.format(new String(out.toByteArray(),
"UTF8"), path);
resp.setContentType("application/x-java-jnlp-file");
OutputStream o = resp.getOutputStream();
o.write(string.getBytes("UTF8"));
o.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private void accept(HttpServletRequest req, HttpServletResponse resp) {
try {
String localAddr = req.getLocalAddr();
Properties properties = EngineFactory.getPropeties();
if (properties.getProperty("hostname") != null) {
localAddr = properties.getProperty("hostname");
}
String path = "http://" + localAddr + ":" + req.getLocalPort() + req.getContextPath();
InputStream is = getClass().getResourceAsStream(
"/com/ramussoft/jnlp/ramus-internet-client.jnlp");
ByteArrayOutputStream out = new ByteArrayOutputStream();
int r;
while ((r = is.read()) >= 0)
out.write(r);
String string = MessageFormat.format(new String(out.toByteArray(),
"UTF8"), path);
resp.setContentType("application/x-java-jnlp-file");
OutputStream o = resp.getOutputStream();
o.write(string.getBytes("UTF8"));
o.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public HttpServletRequestSnapshot(HttpServletRequest request) {
super(request);
authType = request.getAuthType();
characterEncoding = request.getCharacterEncoding();
contentLength = request.getContentLength();
contentType = request.getContentType();
contextPath = request.getContextPath();
cookies = request.getCookies();
requestHeaderNames = request.getHeaderNames();
Enumeration<String> tmp = request.getHeaderNames();
while (tmp.hasMoreElements()) {
String key = tmp.nextElement();
headersMap.put(key, request.getHeaders(key));
}
localAddr = request.getLocalAddr();
local = request.getLocale();
localName = request.getLocalName();
localPort = request.getLocalPort();
method = request.getMethod();
pathInfo = request.getPathInfo();
pathTranslated = request.getPathTranslated();
protocol = request.getProtocol();
queryString = request.getQueryString();
remoteAddr = request.getRemoteAddr();
remoteHost = request.getRemoteHost();
remotePort = request.getRemotePort();
remoteUser = request.getRemoteUser();
requestURI = request.getRequestURI();
requestURL = request.getRequestURL();
requestedSessionId = request.getRequestedSessionId();
schema = request.getScheme();
serverName = request.getServerName();
serverPort = request.getServerPort();
servletPath = request.getServletPath();
if (request.isRequestedSessionIdValid()) {
session = request.getSession();
}
principal = request.getUserPrincipal();
}
/**
* Initialize Monitoring context Must be called before calling any
* scheduleXYZMonitoring REST method
*/
@POST
@Path( "initializeMonitoring")
@Consumes( MediaType.APPLICATION_JSON)
@Produces( MediaType.APPLICATION_JSON)
public Response initializeMonitoring(
@Context HttpServletRequest request,
BasePojo basePojo ) {
final String caller = getCaller(request, basePojo, false);
ThreadsPerCaller.registerThread(caller);
try {
SessionData sd = getSessionData(request, basePojo);
RestSystemMonitor restSystemMonitor = sd.getSystemMonitor();
String agent = request.getLocalAddr() + ":" + request.getLocalPort();
restSystemMonitor.initializeMonitoringContext(agent);
return Response.ok("{\"status\":\"monitoring context initialized.\"}").build();
} catch (Exception e) {
return Response.serverError().entity(new ErrorPojo(e)).build();
} finally {
ThreadsPerCaller.unregisterThread();
}
}
@POST
@Path( "scheduleSystemMonitoring")
@Consumes( MediaType.APPLICATION_JSON)
@Produces( MediaType.APPLICATION_JSON)
public Response scheduleSystemMonitoring(
@Context HttpServletRequest request,
ScheduleSystemMonitoringPojo monitoringPojo ) {
final String caller = getCaller(request, monitoringPojo, false);
ThreadsPerCaller.registerThread(caller);
try {
SessionData sd = getSessionData(request, monitoringPojo);
RestSystemMonitor restSystemMonitor = sd.getSystemMonitor();
String agent = request.getLocalAddr() + ":" + request.getLocalPort();
Set<ReadingBean> readings = restSystemMonitor.scheduleSystemMonitoring(agent,
monitoringPojo.getReadings());
restSystemMonitor.setScheduledReadingTypes(readings);
return Response.ok("{\"status\":\"scheduled system monitoring for readings '"
+ Arrays.toString(monitoringPojo.getReadings()) + "'\"}")
.build();
} catch (Exception e) {
return Response.serverError().entity(new ErrorPojo(e)).build();
} finally {
ThreadsPerCaller.unregisterThread();
}
}
@POST
@Path( "scheduleMonitoring")
@Consumes( MediaType.APPLICATION_JSON)
@Produces( MediaType.APPLICATION_JSON)
public Response scheduleMonitoring(
@Context HttpServletRequest request,
ScheduleMonitoringPojo monitoringPojo ) {
final String caller = getCaller(request, monitoringPojo, false);
ThreadsPerCaller.registerThread(caller);
try {
SessionData sd = getSessionData(request, monitoringPojo);
RestSystemMonitor restSystemMonitor = sd.getSystemMonitor();
String agent = request.getLocalAddr() + ":" + request.getLocalPort();
Set<ReadingBean> readings = restSystemMonitor.scheduleMonitoring(agent,
monitoringPojo.getReading(),
monitoringPojo.getReadingParametersAsMap());
restSystemMonitor.setScheduledReadingTypes(readings);
String readingParametersAsString = entrySetAsString(monitoringPojo.getReadingParametersAsMap());
return Response.ok("{\"status\":\"scheduled monitoring for reading '"
+ monitoringPojo.getReading() + "' and readingParameters '"
+ readingParametersAsString + "'\"}")
.build();
} catch (Exception e) {
return Response.serverError().entity(new ErrorPojo(e)).build();
} finally {
ThreadsPerCaller.unregisterThread();
}
}
public static ArrayList<String> getTrustetRefererHosts(HttpServletRequest request) {
ArrayList<String> referers = CommonUtil.getValueStringList(SettingCodes.TRUSTED_REFERER_HOSTS, getBundle(Bundle.SETTINGS), DefaultSettings.TRUSTED_REFERER_HOSTS);
ArrayList<String> result = new ArrayList<String>(referers.size());
Iterator<String> it = referers.iterator();
while (it.hasNext()) {
String referer = it.next();
String substitution;
if (referer.equalsIgnoreCase(DefaultSettings.LOCAL_ADDR_REFERER)) {
if (request != null) {
substitution = request.getLocalAddr();
if (!CommonUtil.isEmptyString(substitution)) {
result.add(substitution);
}
}
} else if (referer.equalsIgnoreCase(DefaultSettings.LOCAL_NAME_REFERER)) {
if (request != null) {
substitution = request.getLocalName();
if (!CommonUtil.isEmptyString(substitution)) {
result.add(substitution);
}
}
} else if (referer.equalsIgnoreCase(DefaultSettings.HTTP_DOMAIN_REFERER)) {
substitution = WebUtil.getHttpDomainName();
if (!CommonUtil.isEmptyString(substitution)) {
result.add(substitution);
}
} else {
result.add(referer);
}
}
return result;
}
@POST
@Path( "scheduleCustomJvmMonitoring")
@Consumes( MediaType.APPLICATION_JSON)
@Produces( MediaType.APPLICATION_JSON)
public Response scheduleCustomJvmMonitoring(
@Context HttpServletRequest request,
ScheduleCustomJvmMonitoringPojo monitoringPojo ) {
final String caller = getCaller(request, monitoringPojo, false);
ThreadsPerCaller.registerThread(caller);
try {
SessionData sd = getSessionData(request, monitoringPojo);
RestSystemMonitor restSystemMonitor = sd.getSystemMonitor();
String agent = request.getLocalAddr() + ":" + request.getLocalPort();
Set<ReadingBean> readings = restSystemMonitor.scheduleCustomJvmMonitoring(agent,
monitoringPojo.getJmxPort(),
monitoringPojo.getAlias(),
monitoringPojo.getMbeanName(),
monitoringPojo.getUnit(),
monitoringPojo.getMbeanAttributes());
restSystemMonitor.setScheduledReadingTypes(readings);
} catch (Exception e) {
return Response.serverError().entity(new ErrorPojo(e)).build();
} finally {
ThreadsPerCaller.unregisterThread();
}
String statusMessage = "{\"status \": \"scheduled custom JVM monitoring with parameters '"
+ monitoringPojo.toString() + "'\"}";
return Response.ok(statusMessage).build();
}
@POST
@Path( "scheduleUserActivity")
@Consumes( MediaType.APPLICATION_JSON)
@Produces( MediaType.APPLICATION_JSON)
public Response scheduleUserActivity(
@Context HttpServletRequest request,
BasePojo basePojo ) {
final String caller = getCaller(request, basePojo, false);
ThreadsPerCaller.registerThread(caller);
try {
SessionData sd = getSessionData(request, basePojo);
RestSystemMonitor restSystemMonitor = sd.getSystemMonitor();
String agent = request.getLocalAddr() + ":" + request.getLocalPort();
restSystemMonitor.scheduleUserActivity(agent);
} catch (Exception e) {
return Response.serverError().entity(new ErrorPojo(e)).build();
} finally {
ThreadsPerCaller.unregisterThread();
}
String statusMessage = "{\"status \": \"scheduled user activity monitoring.\"}";
return Response.ok(statusMessage).build();
}
@POST
@Path( "startMonitoring")
@Consumes( MediaType.APPLICATION_JSON)
@Produces( MediaType.APPLICATION_JSON)
public Response startMonitoring(
@Context HttpServletRequest request,
StartMonitoringPojo monitoringPojo ) {
final String caller = getCaller(request, monitoringPojo, false);
ThreadsPerCaller.registerThread(caller);
try {
SessionData sd = getSessionData(request, monitoringPojo);
RestSystemMonitor restSystemMonitor = sd.getSystemMonitor();
String agent = request.getLocalAddr() + ":" + request.getLocalPort();
// calculate the time offset between the agent and the test executor
long timeOffset = System.currentTimeMillis() - monitoringPojo.getStartTimestamp();
restSystemMonitor.startMonitoring(agent,
monitoringPojo.getStartTimestamp(),
monitoringPojo.getPollingInterval(),
timeOffset);
return Response.ok("{\"status\":\"monitoring started on every "
+ monitoringPojo.getPollingInterval() + " seconds.\"}")
.build();
} catch (Exception e) {
return Response.serverError().entity(new ErrorPojo(e)).build();
} finally {
ThreadsPerCaller.unregisterThread();
}
}
@RequestMapping("/main")
public ModelAndView toMain(HttpServletRequest request){
ModelAndView modelAndView=new ModelAndView("admin/main");
String clientIp=request.getRemoteAddr(); //获取客户端IP,如:127.0.0.1
String hostIp=request.getLocalAddr();
int hostPort=request.getLocalPort();
Date date = new Date();
SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm");//设置日期格式
String dates = df.format(date);
Admin admin=(Admin) request.getSession().getAttribute("admin");
AdminLoginLog lastLoginLog=null;
try {
if (adminLoginLogService.selectRencent(admin.getId())!=null && adminLoginLogService.selectRencent(admin.getId()).size()==2){
List<AdminLoginLog> adminLoginLogs=adminLoginLogService.selectRencent(admin.getId());
lastLoginLog=adminLoginLogs.get(1);
}
}catch (Exception e){
e.printStackTrace();
}finally {
int articleCount=articleService.selectCount();
int commentCount=commentService.countAllNum();
int loginNum=adminLoginLogService.selectCountByAdminId(admin.getId());
modelAndView.addObject("clientIp",clientIp);
modelAndView.addObject("hostIp",hostIp);
modelAndView.addObject("hostPort",hostPort);
modelAndView.addObject("date",dates);
if (lastLoginLog!=null){
modelAndView.addObject("loginLog",lastLoginLog);
}
modelAndView.addObject("articleCount",articleCount);
modelAndView.addObject("commentCount",commentCount);
modelAndView.addObject("loginNum",loginNum);
return modelAndView;
}
}
public ServletRequestCopy(HttpServletRequest request) {
this.servletPath = request.getServletPath();
this.contextPath = request.getContextPath();
this.pathInfo = request.getPathInfo();
this.requestUri = request.getRequestURI();
this.requestURL = request.getRequestURL();
this.method = request.getMethod();
this.serverName = request.getServerName();
this.serverPort = request.getServerPort();
this.protocol = request.getProtocol();
this.scheme = request.getScheme();
/*
* have to comment out below two lines as otherwise web socket will
* report UnSupportedOperationException upon connection
*/
//this.characterEncoding = request.getCharacterEncoding();
//this.contentType = request.getContentType();
//this.requestedSessionId = request.getRequestedSessionId();
this.characterEncoding = null;
this.contentType = null;
this.requestedSessionId = null;
this.locale = request.getLocale();
this.locales = request.getLocales();
this.isSecure = request.isSecure();
this.remoteUser = request.getRemoteUser();
this.remoteAddr = request.getRemoteAddr();
this.remoteHost = request.getRemoteHost();
this.remotePort = request.getRemotePort();
this.localAddr = request.getLocalAddr();
this.localName = request.getLocalName();
this.localPort = request.getLocalPort();
this.pathTranslated = request.getPathTranslated();
this.principal = request.getUserPrincipal();
HttpSession session = request.getSession(true);
httpSession = new HttpSessionCopy(session);
String s;
Enumeration<String> e = request.getHeaderNames();
while (e != null && e.hasMoreElements()) {
s = e.nextElement();
Enumeration<String> headerValues = request.getHeaders(s);
this.headers.put(s, headerValues);
}
e = request.getAttributeNames();
while (e != null && e.hasMoreElements()) {
s = e.nextElement();
attributes.put(s, request.getAttribute(s));
}
e = request.getParameterNames();
while (e != null && e.hasMoreElements()) {
s = e.nextElement();
parameters.put(s, request.getParameterValues(s));
}
}
/**
* Tell the DbEventRequestProcess which run and test must receive the DB
* messages/data
*/
@POST
@Path( "joinTestcase")
@Consumes( MediaType.APPLICATION_JSON)
@Produces( MediaType.APPLICATION_JSON)
public Response joinTestcase(
@Context HttpServletRequest request,
JoinTestcasePojo testCaseStatePojo ) {
final String caller = getCaller(request, testCaseStatePojo, false);
ThreadsPerCaller.registerThread(caller);
try {
SessionData sd = getSessionData(request, testCaseStatePojo);
RestSystemMonitor restSystemMonitor = sd.getSystemMonitor();
// cancel all action tasks, that are started on an agent, located on
// the current caller host.
// current caller and the agent must have the same IP, in order for
// the queue to be cancelled
dbLog.debug("Cancelling all action task on the agent, that were started form the current caller.");
MultiThreadedActionHandler.cancellAllQueuesFromAgent(ThreadsPerCaller.getCaller());
// cancel all running system monitoring tasks on the agent
dbLog.debug("Cancelling all running system monitoring tasks on the agent, that were started form the current caller.");
String agent = request.getLocalAddr() + ":" + request.getLocalPort();
restSystemMonitor.stopMonitoring(agent);
TestCaseState newTestCaseState = new TestCaseState();
newTestCaseState.setRunId(testCaseStatePojo.getRunId());
newTestCaseState.setTestcaseId(testCaseStatePojo.getTestcaseId());
newTestCaseState.setLastExecutedTestcaseId(testCaseStatePojo.getLastExecutedTestcaseId());
// get the current state on the agent
TestCaseState currentState = dbLog.getCurrentTestCaseState();
boolean joinToNewTescase = true;
if (currentState != null && currentState.isInitialized()) {
/* This agent is already configured.
*
* Now check if the state is the same as the new one, this would mean we are trying to
* configure this agent for second time.
* This is normal as we get here when Test Executor or another agent calls this agent for first time.
*
* If the state is different, we hit an error which means this agent did not get On Test End event
* for the previous test case.
*/
if (!currentState.equals(newTestCaseState)) {
dbLog.error("This test appears to be aborted by the user on the test executor side, but it kept running on the agent side."
+ " Now we cancel any further logging from the agent.");
dbLog.leaveTestCase();
} else {
joinToNewTescase = false;
}
}
if (joinToNewTescase) {
/* previous RestSystemMonitor instance is still in the sessionData for that caller
* so we create new RestSystemMonitor for this caller
* */
restSystemMonitor = new RestSystemMonitor();
sd.setSystemMonitor(restSystemMonitor);
dbLog.joinTestCase(newTestCaseState);
logClassPath(newTestCaseState);
return Response.ok("{\"status\": \"testcase joined.\"}").build();
} else {
return Response.ok("{\"status\": \"testcase already joined.\"}").build();
}
} catch (Exception e) {
return Response.serverError().entity(new ErrorPojo(e)).build();
} finally {
ThreadsPerCaller.unregisterThread();
}
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
servletRequest.setCharacterEncoding("UTF-8");
final HttpServletRequest request = (HttpServletRequest)servletRequest;
KeycloakSessionFactory sessionFactory = (KeycloakSessionFactory) servletRequest.getServletContext().getAttribute(KeycloakSessionFactory.class.getName());
KeycloakSession session = sessionFactory.create();
Resteasy.pushContext(KeycloakSession.class, session);
ClientConnection connection = new ClientConnection() {
@Override
public String getRemoteAddr() {
return request.getRemoteAddr();
}
@Override
public String getRemoteHost() {
return request.getRemoteHost();
}
@Override
public int getRemotePort() {
return request.getRemotePort();
}
@Override
public String getLocalAddr() {
return request.getLocalAddr();
}
@Override
public int getLocalPort() {
return request.getLocalPort();
}
};
session.getContext().setConnection(connection);
Resteasy.pushContext(ClientConnection.class, connection);
KeycloakTransaction tx = session.getTransactionManager();
Resteasy.pushContext(KeycloakTransaction.class, tx);
tx.begin();
try {
filterChain.doFilter(servletRequest, servletResponse);
} finally {
if (servletRequest.isAsyncStarted()) {
servletRequest.getAsyncContext().addListener(createAsyncLifeCycleListener(session));
} else {
closeSession(session);
}
}
}
private String getAgentHostAddress() {
MessageContext msgx = wsContext.getMessageContext();
HttpServletRequest request = ((HttpServletRequest) msgx.get(MessageContext.SERVLET_REQUEST));
return request.getLocalAddr() + ":" + request.getLocalPort();
}