Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  package net.nan21.dnet.core.web.controller;
  
  import java.io.File;
  import java.util.HashMap;
 import java.util.Map;
 
 import  javax.servlet.ServletOutputStream;
 import  javax.servlet.http.HttpServletRequest;
 import  javax.servlet.http.HttpServletResponse;
 
 
 import  org.codehaus.jackson.map.DeserializationConfig;
 import  org.codehaus.jackson.map.ObjectMapper;
 import  org.codehaus.jackson.map.SerializationConfig;
 import  org.springframework.http.HttpStatus;
 import  org.springframework.security.core.context.SecurityContextHolder;
 import  org.springframework.web.bind.annotation.ExceptionHandler;
 import  org.springframework.web.bind.annotation.ResponseBody;

Root of the abstract controllers hierarchy.

Author(s):
amathe
 
 public abstract class AbstractDnetController implements ApplicationContextAware {
 
System configuration. May be null, use the getter.
 
Product information to be displayed on client.
 
 	protected IProductInfo productInfo;

Presenter service locator. May be null, use the getter.
 
Authorization factory. May be null, use the getter.
 
Default transfer buffer size.
 
 	protected final static int FILE_TRANSFER_BUFFER_SIZE = 4 * 1024;
 
 	final static Logger logger = LoggerFactory
 
 	protected void prepareRequest(HttpServletRequest request,
 			HttpServletResponse responsethrows Exception {
 
 		request.setCharacterEncoding("UTF-8");
 		response.setCharacterEncoding("UTF-8");
 
 		User user;
 		Params params;
 		UserProfile profile;
 
 		try {
 			su = (SessionUser) SecurityContextHolder.getContext()
 					.getAuthentication().getPrincipal();
 			user = (Usersu.getUser();
 			params = (Paramssu.getParams();
 			profile = new UserProfile(su.isAdministrator(), su.getRoles());
 
 		} catch (ClassCastException e) {
 			if (.isDebugEnabled()) {
 				.debug("Not authenticated request denied.");
 			}
			throw new Exception("<b>Session expired.</b>"
"<br> Logout from application and login again.");
		}
		if (checkIp != null && checkIp.equals("true")) {
" enabled, checking IP against login IP...");
			}
			String ip = request.getRemoteAddr();
			if (!su.getClientIp().equals(ip)) {
				.debug("Request comes from different IP as expected. Expected: "
su.getClientIp() + ", real " + ip);
				throw new Exception(
						"Security settings do not allow to process request. Check log file for details.");
			}
		}
		String checkAgent = this.getSystemConfig().getSysParamValue(
		if (checkAgent != null && checkAgent.equals("true")) {
" enabled, checking user-agent agianst login user-agent...");
			}
			String agent = request.getHeader("User-Agent");
			if (!su.getUserAgent().equals(agent)) {
				.debug("Request comes from different user-agent as expected. Expected: "
su.getUserAgent() + ", real " + agent);
				throw new Exception(
						"Security settings do not allow to process request. Check log file for details.");
			}
		}
	}
	protected void finishRequest() {
	}

Collect parameters from request. ATTENTION!: Only the first value is considered.

Parameters:
request
prefix Collect only parameters which start with this prefix
suffix Collect only parameters which ends with this suffix
Returns:
	protected Map<StringStringcollectParams(HttpServletRequest request,
			String prefixString suffix) {
		@SuppressWarnings("unchecked")
		Map<StringString[]> paramMap = (Map<StringString[]>) request
				.getParameterMap();
		Map<StringStringresult = new HashMap<StringString>();
		for (Map.Entry<StringString[]> e : paramMap.entrySet()) {
			String k = e.getKey();
			if (prefix != null && k.startsWith(prefix)) {
				if (suffix != null && k.endsWith(suffix)) {
					result.put(ke.getValue()[0]);
				}
			}
		}
		return result;
	}
	protected ObjectMapper getJsonMapper() {
		ObjectMapper mapper = new ObjectMapper();
		mapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS,
				false);
		mapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false);
		mapper.configure(
				DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
		return mapper;
	}
	// private String buildErrorMessage(String msg) {
	// ObjectMapper mapper = getJsonMapper();
	// try {
	// return "{ \"success\":false, \"msg\":"
	// + mapper.writeValueAsString(msg) + "}";
	// } catch (Exception e) {
	// e.printStackTrace();
	// return
	// "{ \"success\": false, \"msg\": \"There was an error while trying to serialize the business logic exception. Check the application logs for more details. \"}";
	// }
	// }
	protected void sendFile(File file, ServletOutputStream outputStream)
			throws IOException {
		this.sendFile(fileoutputStream);
	}
	protected void sendFile(File file, ServletOutputStream outputStream,
			int bufferSizethrows IOException {
		InputStream in = null;
		try {
			in = new BufferedInputStream(new FileInputStream(file));
			byte[] buf = new byte[bufferSize];
			int bytesRead;
			while ((bytesRead = in.read(buf)) != -1) {
				outputStream.write(buf, 0, bytesRead);
			}
finally {
			if (in != null)
				in.close();
		}
		outputStream.flush();
	}
	protected void sendFile(InputStream inputStream,
			ServletOutputStream outputStreamthrows IOException {
		this.sendFile(inputStreamoutputStream);
	}
	protected void sendFile(InputStream inputStream,
			ServletOutputStream outputStreamint bufferSize)
			throws IOException {
		try {
			byte[] buf = new byte[bufferSize];
			int bytesRead;
			while ((bytesRead = inputStream.read(buf)) != -1) {
				outputStream.write(buf, 0, bytesRead);
			}
finally {
			if (inputStream != null)
				inputStream.close();
		}
		outputStream.flush();
	}
	/* ================ EXCEPTIONS ======================== */

Not authenticated

Parameters:
e
response
Returns:
Throws:
IOException
	@ExceptionHandler(value = NotAuthorizedRequestException.class)
	@ResponseBody
			HttpServletResponse responsethrows IOException {
		response.setStatus(403);
		if (e.getCause() != null) {
			response.getOutputStream().print(e.getCause().getMessage());
else {
			response.getOutputStream().print(e.getMessage());
		}
		return null;
	}

Generic exception handler

Parameters:
e
response
Returns:
Throws:
IOException
	@ExceptionHandler(value = Exception.class)
	@ResponseBody
	protected String handleException(Exception e, HttpServletResponse response)
			throws IOException {
		if (e instanceof NotAuthorizedRequestException) {
					response);
else if (e instanceof InvocationTargetException) {
			StringBuffer sb = new StringBuffer();
			if (e.getMessage() != null) {
				sb.append(e.getMessage() + "\n");
			}
			if (exc.getMessage() != null) {
				sb.append(exc.getMessage() + "\n");
			}
			if (exc.getCause() != null) {
				if (sb.length() > 0) {
					sb.append(" Reason: ");
				}
			}
			response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
			response.getOutputStream().print(sb.toString());
			return null;
		}
		StringBuffer sb = new StringBuffer();
		if (e.getLocalizedMessage() != null) {
		}
		if (e.getCause() != null) {
			if (sb.length() > 0) {
				sb.append(" Reason: ");
			}
		}
		response.setStatus(HttpStatus.EXPECTATION_FAILED.value());
		response.getOutputStream().print(sb.toString());
		return null;
		// response.setStatus(HttpStatus.EXPECTATION_FAILED.value());
		// return this.buildErrorMessage(e.getMessage());
	}
	/* ================= GETTERS - SETTERS ================== */
	}
	public void setApplicationContext(ApplicationContext applicationContext) {
		this. = applicationContext;
	}

Get system configuration object. If it is null attempts to retrieve it from Spring context.

Returns:
		if (this. == null) {
		}
		return ;
	}

Set system configuration object

Parameters:
systemConfig
	public void setSystemConfig(ISystemConfig systemConfig) {
		this. = systemConfig;
	}

Get product info object. If it is null attempts to retrieve it from Spring context.

Returns:
		if (this. == null) {
		}
		return ;
	}
	public void setProductInfo(IProductInfo productInfo) {
		this. = productInfo;
	}

Get presenter service locator. If it is null attempts to retrieve it from Spring context.

Returns:
		if (this. == null) {
		}
	}

Set presenter service locator.

Parameters:
serviceLocator
	public void setServiceLocator(ServiceLocator serviceLocator) {
		this. = serviceLocator;
	}

Get authorization factory. If it is null attempts to retrieve it from Spring context.

Returns:
Throws:
Exception
		if (this. == null) {
		}
	}

Set authorization factory.

Parameters:
authorizationFactory
			IAuthorizationFactory authorizationFactory) {
		this. = authorizationFactory;
	}

Authorize an assignment action.

Parameters:
asgnName
action
Throws:
Exception
	protected void authorizeAsgnAction(String asgnNameString action)
			throws Exception {
				.authorize(asgnNameaction);
	}

Authorize a DS action.

Parameters:
asgnName
action
Throws:
Exception
	protected void authorizeDsAction(String dsNameString action)
			throws Exception {
				.authorize(dsNameaction);
	}
New to GrepCode? Check out our FAQ X