List of usage examples for javax.xml.ws.handler MessageContext SERVLET_REQUEST
String SERVLET_REQUEST
To view the source code for javax.xml.ws.handler MessageContext SERVLET_REQUEST.
Click Source Link
From source file:com.netsteadfast.greenstep.bsc.webservice.impl.ApiWebServiceImpl.java
@WebMethod @GET//from w w w . j a v a 2s. c o m @Path("/scorecard2/") @Override public BscApiServiceResponse getScorecard2(@WebParam(name = "visionId") @QueryParam("visionId") String visionId, @WebParam(name = "startDate") @QueryParam("startDate") String startDate, @WebParam(name = "endDate") @QueryParam("endDate") String endDate, @WebParam(name = "startYearDate") @QueryParam("startYearDate") String startYearDate, @WebParam(name = "endYearDate") @QueryParam("endYearDate") String endYearDate, @WebParam(name = "frequency") @QueryParam("frequency") String frequency, @WebParam(name = "dataFor") @QueryParam("dataFor") String dataFor, @WebParam(name = "measureDataOrganizationId") @QueryParam("measureDataOrganizationId") String measureDataOrganizationId, @WebParam(name = "measureDataEmployeeId") @QueryParam("measureDataEmployeeId") String measureDataEmployeeId, @WebParam(name = "contentFlag") @QueryParam("contentFlag") String contentFlag) throws Exception { HttpServletRequest request = null; if (this.getWebServiceContext() != null && this.getWebServiceContext().getMessageContext() != null) { request = (HttpServletRequest) this.getWebServiceContext().getMessageContext() .get(MessageContext.SERVLET_REQUEST); } Subject subject = null; BscApiServiceResponse responseObj = new BscApiServiceResponse(); responseObj.setSuccess(YesNo.NO); try { subject = WsAuthenticateUtils.login(); @SuppressWarnings("unchecked") IVisionService<VisionVO, BbVision, String> visionService = (IVisionService<VisionVO, BbVision, String>) AppContext .getBean("bsc.service.VisionService"); @SuppressWarnings("unchecked") IEmployeeService<EmployeeVO, BbEmployee, String> employeeService = (IEmployeeService<EmployeeVO, BbEmployee, String>) AppContext .getBean("bsc.service.EmployeeService"); @SuppressWarnings("unchecked") IOrganizationService<OrganizationVO, BbOrganization, String> organizationService = (IOrganizationService<OrganizationVO, BbOrganization, String>) AppContext .getBean("bsc.service.OrganizationService"); String visionOid = ""; String measureDataOrganizationOid = ""; String measureDataEmployeeOid = ""; DefaultResult<VisionVO> visionResult = visionService.findForSimpleByVisId(visionId); if (visionResult.getValue() == null) { throw new Exception(visionResult.getSystemMessage().getValue()); } visionOid = visionResult.getValue().getOid(); if (StringUtils.isBlank(measureDataOrganizationId)) { measureDataOrganizationOid = BscBaseLogicServiceCommonSupport .findEmployeeDataByEmpId(employeeService, measureDataOrganizationId).getOid(); } if (StringUtils.isBlank(measureDataEmployeeId)) { measureDataEmployeeOid = BscBaseLogicServiceCommonSupport .findOrganizationDataByUK(organizationService, measureDataEmployeeId).getOid(); } this.processForScorecard(responseObj, request, visionOid, startDate, endDate, startYearDate, endYearDate, frequency, dataFor, measureDataOrganizationOid, measureDataEmployeeOid, contentFlag); } catch (Exception e) { responseObj.setMessage(e.getMessage()); } finally { if (!YesNo.YES.equals(responseObj.getSuccess())) { responseObj.setMessage(SysMessageUtil.get(GreenStepSysMsgConstants.SEARCH_NO_DATA)); } WsAuthenticateUtils.logout(subject); } subject = null; return responseObj; }
From source file:dk.statsbiblioteket.doms.central.CentralWebserviceImpl.java
private HttpServletRequest getServletRequest() { if (context != null) { return (HttpServletRequest) context.getMessageContext().get(MessageContext.SERVLET_REQUEST); } else {/* ww w . j a v a2s . co m*/ return restRequest; } }
From source file:nl.nn.adapterframework.extensions.cxf.SOAPProviderBase.java
@Override public SOAPMessage invoke(SOAPMessage request) { String result;// ww w. j a v a 2 s.c o m PipeLineSessionBase pipelineSession = new PipeLineSessionBase(); String correlationId = Misc.createSimpleUUID(); log.debug(getLogPrefix(correlationId) + "received message"); if (request == null) { String faultcode = "soap:Server"; String faultstring = "SOAPMessage is null"; String httpRequestMethod = (String) webServiceContext.getMessageContext() .get(MessageContext.HTTP_REQUEST_METHOD); if (!"POST".equals(httpRequestMethod)) { faultcode = "soap:Client"; faultstring = "Request was send using '" + httpRequestMethod + "' instead of 'POST'"; } result = "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" + "<soap:Body><soap:Fault>" + "<faultcode>" + faultcode + "</faultcode>" + "<faultstring>" + faultstring + "</faultstring>" + "</soap:Fault></soap:Body></soap:Envelope>"; } else { // Make mime headers in request available as session key @SuppressWarnings("unchecked") Iterator<MimeHeader> mimeHeaders = request.getMimeHeaders().getAllHeaders(); String mimeHeadersXml = getMimeHeadersXml(mimeHeaders).toXML(); pipelineSession.put("mimeHeaders", mimeHeadersXml); // Make attachments in request (when present) available as session keys int i = 1; XmlBuilder attachments = new XmlBuilder("attachments"); @SuppressWarnings("unchecked") Iterator<AttachmentPart> attachmentParts = request.getAttachments(); while (attachmentParts.hasNext()) { try { InputStreamAttachmentPart attachmentPart = new InputStreamAttachmentPart( attachmentParts.next()); XmlBuilder attachment = new XmlBuilder("attachment"); attachments.addSubElement(attachment); XmlBuilder sessionKey = new XmlBuilder("sessionKey"); sessionKey.setValue("attachment" + i); attachment.addSubElement(sessionKey); pipelineSession.put("attachment" + i, attachmentPart.getInputStream()); log.debug(getLogPrefix(correlationId) + "adding attachment [attachment" + i + "] to session"); @SuppressWarnings("unchecked") Iterator<MimeHeader> attachmentMimeHeaders = attachmentPart.getAllMimeHeaders(); attachment.addSubElement(getMimeHeadersXml(attachmentMimeHeaders)); } catch (SOAPException e) { e.printStackTrace(); log.warn("Could not store attachment in session key", e); } i++; } pipelineSession.put("attachments", attachments.toXML()); // Transform SOAP message to string String message; try { message = XmlUtils.nodeToString(request.getSOAPPart()); log.debug(getLogPrefix(correlationId) + "transforming from SOAP message"); } catch (TransformerException e) { String m = "Could not transform SOAP message to string"; log.error(m, e); throw new WebServiceException(m, e); } // Process message via WebServiceListener ISecurityHandler securityHandler = new WebServiceContextSecurityHandler(webServiceContext); pipelineSession.setSecurityHandler(securityHandler); pipelineSession.put(IPipeLineSession.HTTP_REQUEST_KEY, webServiceContext.getMessageContext().get(MessageContext.SERVLET_REQUEST)); pipelineSession.put(IPipeLineSession.HTTP_RESPONSE_KEY, webServiceContext.getMessageContext().get(MessageContext.SERVLET_RESPONSE)); try { log.debug(getLogPrefix(correlationId) + "processing message"); result = processRequest(correlationId, message, pipelineSession); } catch (ListenerException e) { String m = "Could not process SOAP message: " + e.getMessage(); log.error(m); throw new WebServiceException(m, e); } } // Transform result string to SOAP message SOAPMessage soapMessage = null; try { log.debug(getLogPrefix(correlationId) + "transforming to SOAP message"); soapMessage = getMessageFactory().createMessage(); StreamSource streamSource = new StreamSource(new StringReader(result)); soapMessage.getSOAPPart().setContent(streamSource); } catch (SOAPException e) { String m = "Could not transform string to SOAP message"; log.error(m); throw new WebServiceException(m, e); } String multipartXml = (String) pipelineSession.get(attachmentXmlSessionKey); log.debug(getLogPrefix(correlationId) + "building multipart message with MultipartXmlSessionKey [" + multipartXml + "]"); if (StringUtils.isNotEmpty(multipartXml)) { Element partsElement; try { partsElement = XmlUtils.buildElement(multipartXml); } catch (DomBuilderException e) { String m = "error building multipart xml"; log.error(m, e); throw new WebServiceException(m, e); } Collection<Node> parts = XmlUtils.getChildTags(partsElement, "part"); if (parts == null || parts.size() == 0) { log.warn(getLogPrefix(correlationId) + "no part(s) in multipart xml [" + multipartXml + "]"); } else { Iterator<Node> iter = parts.iterator(); while (iter.hasNext()) { Element partElement = (Element) iter.next(); //String partType = partElement.getAttribute("type"); String partName = partElement.getAttribute("name"); String partSessionKey = partElement.getAttribute("sessionKey"); String partMimeType = partElement.getAttribute("mimeType"); Object partObject = pipelineSession.get(partSessionKey); if (partObject instanceof InputStream) { InputStream fis = (InputStream) partObject; DataHandler dataHander = null; try { dataHander = new DataHandler(new ByteArrayDataSource(fis, partMimeType)); } catch (IOException e) { String m = "Unable to add session key '" + partSessionKey + "' as attachment"; log.error(m, e); throw new WebServiceException(m, e); } AttachmentPart attachmentPart = soapMessage.createAttachmentPart(dataHander); attachmentPart.setContentId(partName); soapMessage.addAttachmentPart(attachmentPart); log.debug(getLogPrefix(correlationId) + "appended filepart [" + partSessionKey + "] with value [" + partObject + "] and name [" + partName + "]"); } else { //String String partValue = (String) partObject; DataHandler dataHander = new DataHandler(new ByteArrayDataSource(partValue, partMimeType)); AttachmentPart attachmentPart = soapMessage.createAttachmentPart(dataHander); attachmentPart.setContentId(partName); soapMessage.addAttachmentPart(attachmentPart); log.debug(getLogPrefix(correlationId) + "appended stringpart [" + partSessionKey + "] with value [" + partValue + "]"); } } } } return soapMessage; }
From source file:org.apache.axis2.jaxws.context.WebServiceContextImpl.java
public Principal getUserPrincipal() { // Note that the MessageContext might not be set up yet, or it // may have been released because the lifetime of the WebServiceContext is completed. if (log.isDebugEnabled()) { if (soapMessageContext == null) { log.debug("The MessageContext is not available"); }//from www . j a v a2s . co m } if (soapMessageContext != null) { HttpServletRequest request = (HttpServletRequest) soapMessageContext .get(MessageContext.SERVLET_REQUEST); if (request != null) { if (log.isDebugEnabled()) { log.debug("Access to the user Principal was requested."); } return request.getUserPrincipal(); } else { if (log.isDebugEnabled()) { log.debug("No HttpServletRequest object was found, so no Principal can be found."); } } } return null; }
From source file:org.apache.axis2.jaxws.context.WebServiceContextImpl.java
public boolean isUserInRole(String user) { // Note that the MessageContext might not be set up yet, or it // may have been released because the lifetime of the WebServiceContext is completed. if (log.isDebugEnabled()) { if (soapMessageContext == null) { log.debug("The MessageContext is not available"); }/*from w w w .java2 s . c om*/ } if (soapMessageContext != null) { HttpServletRequest request = (HttpServletRequest) soapMessageContext .get(MessageContext.SERVLET_REQUEST); if (request != null) { if (log.isDebugEnabled()) { log.debug("Checking to see if the user in the role."); } return request.isUserInRole(user); } else { if (log.isDebugEnabled()) { log.debug("No HttpServletRequest object was found, so no role check can be performed."); } } } return false; }
From source file:org.apache.juddi.api.impl.AuthenticatedService.java
public UddiEntityPublisher getEntityPublisher(EntityManager em, String authInfo) throws DispositionReportFaultMessage { if (authInfo == null || authInfo.length() == 0) throw new AuthTokenRequiredException(new ErrorMessage("errors.auth.AuthRequired")); org.apache.juddi.model.AuthToken modelAuthToken = em.find(org.apache.juddi.model.AuthToken.class, authInfo); if (modelAuthToken == null) throw new AuthTokenRequiredException(new ErrorMessage("errors.auth.AuthInvalid")); int allowedMinutesOfInactivity = 0; try {//from w ww. j a v a 2 s . co m allowedMinutesOfInactivity = AppConfig.getConfiguration().getInt(Property.JUDDI_AUTH_TOKEN_TIMEOUT, 0); } catch (ConfigurationException ce) { logger.error("Error reading property " + Property.JUDDI_AUTH_TOKEN_EXPIRATION + " from " + "the application's configuration. No automatic timeout token invalidation will occur. " + ce.getMessage(), ce); } int maxMinutesOfAge = 0; try { maxMinutesOfAge = AppConfig.getConfiguration().getInt(Property.JUDDI_AUTH_TOKEN_EXPIRATION, 0); } catch (ConfigurationException ce) { logger.error("Error reading property " + Property.JUDDI_AUTH_TOKEN_EXPIRATION + " from " + "the application's configuration. No automatic timeout token invalidation will occur. " + ce.getMessage(), ce); } Date now = new Date(); // 0 or negative means token does not expire if (allowedMinutesOfInactivity > 0) { // expire tokens after # minutes of inactivity // compare the time in milli-seconds if (now.getTime() > modelAuthToken.getLastUsed().getTime() + allowedMinutesOfInactivity * 60000l) { logger.info("AUDIT: FAILTURE Token " + modelAuthToken.getAuthToken() + " expired due to inactivity " + getRequestorsIPAddress()); modelAuthToken.setTokenState(AUTHTOKEN_RETIRED); } } if (maxMinutesOfAge > 0) { // expire tokens when max age is reached // compare the time in milli-seconds if (now.getTime() > modelAuthToken.getCreated().getTime() + maxMinutesOfAge * 60000l) { logger.info("AUDIT: FAILURE - Token " + modelAuthToken.getAuthorizedName() + " expired due to old age " + getRequestorsIPAddress()); modelAuthToken.setTokenState(AUTHTOKEN_RETIRED); } } if (modelAuthToken.getTokenState() == AUTHTOKEN_RETIRED) { throw new AuthTokenExpiredException(new ErrorMessage("errors.auth.AuthTokenExpired")); } if (ctx != null) { try { boolean check = true; try { check = AppConfig.getConfiguration().getBoolean(Property.JUDDI_AUTH_TOKEN_ENFORCE_SAME_IP, true); } catch (ConfigurationException ex) { logger.warn("Error loading config property " + Property.JUDDI_AUTH_TOKEN_ENFORCE_SAME_IP + " Enforcing Same IP for Auth Tokens will be enabled by default", ex); } if (check) { MessageContext mc = ctx.getMessageContext(); HttpServletRequest req = null; if (mc != null) { req = (HttpServletRequest) mc.get(MessageContext.SERVLET_REQUEST); } if (req != null && modelAuthToken.getIPAddress() != null && modelAuthToken.getIPAddress() != null && !modelAuthToken.getIPAddress().equalsIgnoreCase(req.getRemoteAddr())) { modelAuthToken.setTokenState(AUTHTOKEN_RETIRED); logger.error( "AUDIT FAILURE - Security Alert - Attempt to use issued auth token from a different IP address, user " + modelAuthToken.getAuthorizedName() + ", issued IP " + modelAuthToken.getIPAddress() + ", attempted use from " + req.getRemoteAddr() + ", forcing reauthentication."); throw new AuthTokenRequiredException(new ErrorMessage("errors.auth.AuthInvalid")); //invalidate the token, someone's intercepted it or it was reused on another ip } } } catch (Exception ex) { if (ex instanceof AuthTokenRequiredException) throw (AuthTokenRequiredException) ex; logger.error("unexpected error caught looking up requestor's ip address", ex); } } Authenticator authenticator = AuthenticatorFactory.getAuthenticator(); UddiEntityPublisher entityPublisher = authenticator.identify(authInfo, modelAuthToken.getAuthorizedName()); // Must make sure the returned publisher has all the necessary fields filled if (entityPublisher == null) { logger.warn( "AUDIT FAILURE - Auth token invalided, publisher does not exist " + getRequestorsIPAddress()); throw new AuthTokenRequiredException(new ErrorMessage("errors.auth.AuthInvalid")); } if (entityPublisher.getAuthorizedName() == null) { logger.warn("AUDIT FAILURE - Auth token invalided, username does exist" + getRequestorsIPAddress()); throw new AuthTokenRequiredException(new ErrorMessage("errors.auth.AuthInvalid")); } // Auth token is being used. Adjust appropriate values so that it's internal 'expiration clock' is reset. modelAuthToken.setLastUsed(new Date()); modelAuthToken.setNumberOfUses(modelAuthToken.getNumberOfUses() + 1); return entityPublisher; }
From source file:org.apache.juddi.api.impl.AuthenticatedService.java
/** * Attempts to get the requestor's ip address from the servlet context, defaults to null it it can't be * retrieved/* w w w . j ava2s.c om*/ * @return requestor's ip address or null if it's not available */ public String getRequestorsIPAddress() { try { MessageContext mc = ctx.getMessageContext(); HttpServletRequest req = null; if (mc != null) { req = (HttpServletRequest) mc.get(MessageContext.SERVLET_REQUEST); } if (req != null) { return req.getRemoteAddr(); } } catch (Exception ex) { logger.debug("Error caught looking up the requestor's ip address", ex); } return null; }
From source file:org.apache.juddi.v3.auth.HTTPContainerAuthenticator.java
@Override public UddiEntityPublisher identify(String authInfoNotused, String authorizedNameNotused, WebServiceContext ctx) throws AuthenticationException, FatalErrorException { int MaxBindingsPerService = -1; int MaxServicesPerBusiness = -1; int MaxTmodels = -1; int MaxBusinesses = -1; try {/* w w w . j a v a2 s .c om*/ MaxBindingsPerService = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_BINDINGS_PER_SERVICE, -1); MaxServicesPerBusiness = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_SERVICES_PER_BUSINESS, -1); MaxTmodels = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_TMODELS_PER_PUBLISHER, -1); MaxBusinesses = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_BUSINESSES_PER_PUBLISHER, -1); } catch (Exception ex) { MaxBindingsPerService = -1; MaxServicesPerBusiness = -1; MaxTmodels = -1; MaxBusinesses = -1; log.error("config exception! ", ex); } EntityManager em = PersistenceManager.getEntityManager(); EntityTransaction tx = em.getTransaction(); try { String user = null; if (ctx == null) throw new UnknownUserException( new ErrorMessage("errors.auth.NoPublisher", "no web service context!")); if (ctx.getUserPrincipal() != null) { user = ctx.getUserPrincipal().getName(); } if (user == null) { MessageContext mc = ctx.getMessageContext(); HttpServletRequest req = null; if (mc != null) { req = (HttpServletRequest) mc.get(MessageContext.SERVLET_REQUEST); } if (req != null && req.getUserPrincipal() != null) { user = req.getUserPrincipal().getName(); } } if (user == null || user.length() == 0) { throw new UnknownUserException(new ErrorMessage("errors.auth.NoPublisher")); } tx.begin(); Publisher publisher = em.find(Publisher.class, user); if (publisher == null) { log.warn("Publisher \"" + user + "\" was not found in the database, adding the publisher in on the fly."); publisher = new Publisher(); publisher.setAuthorizedName(user); publisher.setIsAdmin("false"); publisher.setIsEnabled("true"); publisher.setMaxBindingsPerService(MaxBindingsPerService); publisher.setMaxBusinesses(MaxBusinesses); publisher.setMaxServicesPerBusiness(MaxServicesPerBusiness); publisher.setMaxTmodels(MaxTmodels); publisher.setPublisherName("Unknown"); em.persist(publisher); tx.commit(); } return publisher; } finally { if (tx.isActive()) { tx.rollback(); } em.close(); } }
From source file:org.apache.juddi.v3.auth.HTTPHeaderAuthenticator.java
@Override public UddiEntityPublisher identify(String notusedauthtoken, String notusedusername, WebServiceContext ctx) throws AuthenticationException, FatalErrorException { int MaxBindingsPerService = -1; int MaxServicesPerBusiness = -1; int MaxTmodels = -1; int MaxBusinesses = -1; String http_header_name = null; try {//from w w w. jav a 2 s . c om http_header_name = AppConfig.getConfiguration() .getString(Property.JUDDI_AUTHENTICATOR_HTTP_HEADER_NAME); MaxBindingsPerService = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_BINDINGS_PER_SERVICE, -1); MaxServicesPerBusiness = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_SERVICES_PER_BUSINESS, -1); MaxTmodels = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_TMODELS_PER_PUBLISHER, -1); MaxBusinesses = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_BUSINESSES_PER_PUBLISHER, -1); } catch (Exception ex) { MaxBindingsPerService = -1; MaxServicesPerBusiness = -1; MaxTmodels = -1; MaxBusinesses = -1; log.error("config exception! ", ex); } if (http_header_name == null) { throw new UnknownUserException(new ErrorMessage("errors.auth.NoPublisher", "misconfiguration!")); } EntityManager em = PersistenceManager.getEntityManager(); EntityTransaction tx = em.getTransaction(); try { String user = null; MessageContext mc = ctx.getMessageContext(); HttpServletRequest req = null; if (mc != null) { req = (HttpServletRequest) mc.get(MessageContext.SERVLET_REQUEST); user = req.getHeader(http_header_name); } if (user == null || user.length() == 0) { throw new UnknownUserException(new ErrorMessage("errors.auth.NoPublisher")); } tx.begin(); Publisher publisher = em.find(Publisher.class, user); if (publisher == null) { log.warn("Publisher \"" + user + "\" was not found in the database, adding the publisher in on the fly."); publisher = new Publisher(); publisher.setAuthorizedName(user); publisher.setIsAdmin("false"); publisher.setIsEnabled("true"); publisher.setMaxBindingsPerService(MaxBindingsPerService); publisher.setMaxBusinesses(MaxBusinesses); publisher.setMaxServicesPerBusiness(MaxServicesPerBusiness); publisher.setMaxTmodels(MaxTmodels); publisher.setPublisherName("Unknown"); em.persist(publisher); tx.commit(); } return publisher; } finally { if (tx.isActive()) { tx.rollback(); } em.close(); } }
From source file:org.easyrec.soap.music.impl.MusicShopRecommenderWSImpl.java
private Integer authenticate(String tenant) throws MusicShopRecommenderException { try {/*from w ww . j a v a2 s. c o m*/ MessageContext mc = wsContext.getMessageContext(); HttpServletRequest req = (HttpServletRequest) mc.get(MessageContext.SERVLET_REQUEST); Integer tenantId = authenticationDispatcher.authenticateTenant(tenant, serviceName, req); if (tenantId == null) { throw new MusicShopRecommenderException("Unauthorized access!"); } return tenantId; } catch (Exception e) { throw new MusicShopRecommenderException(e.getMessage()); } }