idx
int64
0
41.2k
question
stringlengths
83
4.15k
target
stringlengths
5
715
23,500
public String getName ( ) { CommonProfile profile = this . getProfile ( ) ; if ( null == principalNameAttribute ) { return profile . getId ( ) ; } Object attrValue = profile . getAttribute ( principalNameAttribute ) ; return ( null == attrValue ) ? null : String . valueOf ( attrValue ) ; }
Returns a name for the principal based upon one of the attributes of the main CommonProfile . The attribute name used to query the CommonProfile is specified in the constructor .
23,501
public static void showBooks ( final ListOfBooks booksList ) { if ( booksList != null && booksList . getBook ( ) != null && ! booksList . getBook ( ) . isEmpty ( ) ) { List < BookType > books = booksList . getBook ( ) ; System . out . println ( "\nNumber of books: " + books . size ( ) ) ; int cnt = 0 ; for ( BookType book : books ) { System . out . println ( "\nBookNum: " + ( cnt ++ + 1 ) ) ; List < PersonType > authors = book . getAuthor ( ) ; if ( authors != null && ! authors . isEmpty ( ) ) { for ( PersonType author : authors ) { System . out . println ( "Author: " + author . getFirstName ( ) + " " + author . getLastName ( ) ) ; } } System . out . println ( "Title: " + book . getTitle ( ) ) ; System . out . println ( "Year: " + book . getYearPublished ( ) ) ; if ( book . getISBN ( ) != null ) { System . out . println ( "ISBN: " + book . getISBN ( ) ) ; } } } else { System . out . println ( "List of books is empty" ) ; } System . out . println ( "" ) ; }
Show books .
23,502
public void contextInitialized ( ServletContextEvent event ) { this . context = event . getServletContext ( ) ; System . out . println ( "The Simple Web App. Is Ready" ) ; ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext ( "/client.xml" ) ; LocatorService client = ( LocatorService ) context . getBean ( "locatorService" ) ; String serviceHost = this . context . getInitParameter ( "serviceHost" ) ; try { client . registerEndpoint ( new QName ( "http://talend.org/esb/examples/" , "GreeterService" ) , serviceHost , BindingType . SOAP_11 , TransportType . HTTP , null ) ; } catch ( InterruptedExceptionFault e ) { e . printStackTrace ( ) ; } catch ( ServiceLocatorFault e ) { e . printStackTrace ( ) ; } }
is ready to service requests
23,503
private void serializeEPR ( EndpointReferenceType wsAddr , Node parent ) throws ServiceLocatorException { try { JAXBElement < EndpointReferenceType > ep = WSA_OBJECT_FACTORY . createEndpointReference ( wsAddr ) ; createMarshaller ( ) . marshal ( ep , parent ) ; } catch ( JAXBException e ) { if ( LOG . isLoggable ( Level . SEVERE ) ) { LOG . log ( Level . SEVERE , "Failed to serialize endpoint data" , e ) ; } throw new ServiceLocatorException ( "Failed to serialize endpoint data" , e ) ; } }
Inserts a marshalled endpoint reference to a given DOM tree rooted by parent .
23,504
private static EndpointReferenceType createEPR ( String address , SLProperties props ) { EndpointReferenceType epr = WSAEndpointReferenceUtils . getEndpointReference ( address ) ; if ( props != null ) { addProperties ( epr , props ) ; } return epr ; }
Creates an endpoint reference from a given adress .
23,505
private static EndpointReferenceType createEPR ( Server server , String address , SLProperties props ) { EndpointReferenceType sourceEPR = server . getEndpoint ( ) . getEndpointInfo ( ) . getTarget ( ) ; EndpointReferenceType targetEPR = WSAEndpointReferenceUtils . duplicate ( sourceEPR ) ; WSAEndpointReferenceUtils . setAddress ( targetEPR , address ) ; if ( props != null ) { addProperties ( targetEPR , props ) ; } return targetEPR ; }
Creates an endpoint reference by duplicating the endpoint reference of a given server .
23,506
private static void addProperties ( EndpointReferenceType epr , SLProperties props ) { MetadataType metadata = WSAEndpointReferenceUtils . getSetMetadata ( epr ) ; ServiceLocatorPropertiesType jaxbProps = SLPropertiesConverter . toServiceLocatorPropertiesType ( props ) ; JAXBElement < ServiceLocatorPropertiesType > slp = SL_OBJECT_FACTORY . createServiceLocatorProperties ( jaxbProps ) ; metadata . getAny ( ) . add ( slp ) ; }
Adds service locator properties to an endpoint reference .
23,507
private static QName getServiceName ( Server server ) { QName serviceName ; String bindingId = getBindingId ( server ) ; EndpointInfo eInfo = server . getEndpoint ( ) . getEndpointInfo ( ) ; if ( JAXRS_BINDING_ID . equals ( bindingId ) ) { serviceName = eInfo . getName ( ) ; } else { ServiceInfo serviceInfo = eInfo . getService ( ) ; serviceName = serviceInfo . getName ( ) ; } return serviceName ; }
Extracts the service name from a Server .
23,508
private static String getBindingId ( Server server ) { Endpoint ep = server . getEndpoint ( ) ; BindingInfo bi = ep . getBinding ( ) . getBindingInfo ( ) ; return bi . getBindingId ( ) ; }
Extracts the bindingId from a Server .
23,509
private static BindingType map2BindingType ( String bindingId ) { BindingType type ; if ( SOAP11_BINDING_ID . equals ( bindingId ) ) { type = BindingType . SOAP11 ; } else if ( SOAP12_BINDING_ID . equals ( bindingId ) ) { type = BindingType . SOAP12 ; } else if ( JAXRS_BINDING_ID . equals ( bindingId ) ) { type = BindingType . JAXRS ; } else { type = BindingType . OTHER ; } return type ; }
Maps a bindingId to its corresponding BindingType .
23,510
private static TransportType map2TransportType ( String transportId ) { TransportType type ; if ( CXF_HTTP_TRANSPORT_ID . equals ( transportId ) || SOAP_HTTP_TRANSPORT_ID . equals ( transportId ) ) { type = TransportType . HTTP ; } else { type = TransportType . OTHER ; } return type ; }
Maps a transportId to its corresponding TransportType .
23,511
private EventTypeEnum getEventType ( Message message ) { boolean isRequestor = MessageUtils . isRequestor ( message ) ; boolean isFault = MessageUtils . isFault ( message ) ; boolean isOutbound = MessageUtils . isOutbound ( message ) ; if ( ! isFault && isRestMessage ( message ) ) { isFault = ( message . getExchange ( ) . get ( "org.apache.cxf.resource.operation.name" ) == null ) ; if ( ! isFault ) { Integer responseCode = ( Integer ) message . get ( Message . RESPONSE_CODE ) ; if ( null != responseCode ) { isFault = ( responseCode >= 400 ) ; } } } if ( isOutbound ) { if ( isFault ) { return EventTypeEnum . FAULT_OUT ; } else { return isRequestor ? EventTypeEnum . REQ_OUT : EventTypeEnum . RESP_OUT ; } } else { if ( isFault ) { return EventTypeEnum . FAULT_IN ; } else { return isRequestor ? EventTypeEnum . RESP_IN : EventTypeEnum . REQ_IN ; } } }
Gets the event type from message .
23,512
protected String getPayload ( Message message ) { try { String encoding = ( String ) message . get ( Message . ENCODING ) ; if ( encoding == null ) { encoding = "UTF-8" ; } CachedOutputStream cos = message . getContent ( CachedOutputStream . class ) ; if ( cos == null ) { LOG . warning ( "Could not find CachedOutputStream in message." + " Continuing without message content" ) ; return "" ; } return new String ( cos . getBytes ( ) , encoding ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } }
Gets the message payload .
23,513
private void handleContentLength ( Event event ) { if ( event . getContent ( ) == null ) { return ; } if ( maxContentLength == - 1 || event . getContent ( ) . length ( ) <= maxContentLength ) { return ; } if ( maxContentLength < CUT_START_TAG . length ( ) + CUT_END_TAG . length ( ) ) { event . setContent ( "" ) ; event . setContentCut ( true ) ; return ; } int contentLength = maxContentLength - CUT_START_TAG . length ( ) - CUT_END_TAG . length ( ) ; event . setContent ( CUT_START_TAG + event . getContent ( ) . substring ( 0 , contentLength ) + CUT_END_TAG ) ; event . setContentCut ( true ) ; }
Handle content length .
23,514
private Map < String , Criteria > getCriterias ( Map < String , String [ ] > params ) { Map < String , Criteria > result = new HashMap < String , Criteria > ( ) ; for ( Map . Entry < String , String [ ] > param : params . entrySet ( ) ) { for ( Criteria criteria : FILTER_CRITERIAS ) { if ( criteria . getName ( ) . equals ( param . getKey ( ) ) ) { try { Criteria [ ] parsedCriterias = criteria . parseValue ( param . getValue ( ) [ 0 ] ) ; for ( Criteria parsedCriteria : parsedCriterias ) { result . put ( parsedCriteria . getName ( ) , parsedCriteria ) ; } } catch ( Exception e ) { LOG . log ( Level . SEVERE , "Error parsing parameter " + param . getKey ( ) , e ) ; } break ; } } } return result ; }
Reads filter parameters .
23,515
public void setSessionTimeout ( int timeout ) { ( ( ZKBackend ) getBackend ( ) ) . setSessionTimeout ( timeout ) ; if ( LOG . isLoggable ( Level . FINE ) ) { LOG . fine ( "Locator session timeout set to: " + timeout ) ; } }
Specify the time out of the session established at the server . The session is kept alive by requests sent by this client object . If the session is idle for a period of time that would timeout the session the client will send a PING request to keep the session alive .
23,516
public void racRent ( ) { pos = pos - 1 ; String userName = CarSearch . getLastSearchParams ( ) [ 0 ] ; String pickupDate = CarSearch . getLastSearchParams ( ) [ 1 ] ; String returnDate = CarSearch . getLastSearchParams ( ) [ 2 ] ; this . searcher . search ( userName , pickupDate , returnDate ) ; if ( searcher != null && searcher . getCars ( ) != null && pos < searcher . getCars ( ) . size ( ) && searcher . getCars ( ) . get ( pos ) != null ) { RESStatusType resStatus = reserver . reserveCar ( searcher . getCustomer ( ) , searcher . getCars ( ) . get ( pos ) , pickupDate , returnDate ) ; ConfirmationType confirm = reserver . getConfirmation ( resStatus , searcher . getCustomer ( ) , searcher . getCars ( ) . get ( pos ) , pickupDate , returnDate ) ; RESCarType car = confirm . getCar ( ) ; CustomerDetailsType customer = confirm . getCustomer ( ) ; System . out . println ( MessageFormat . format ( CONFIRMATION , confirm . getDescription ( ) , confirm . getReservationId ( ) , customer . getName ( ) , customer . getEmail ( ) , customer . getCity ( ) , customer . getStatus ( ) , car . getBrand ( ) , car . getDesignModel ( ) , confirm . getFromDate ( ) , confirm . getToDate ( ) , padl ( car . getRateDay ( ) , 10 ) , padl ( car . getRateWeekend ( ) , 10 ) , padl ( confirm . getCreditPoints ( ) . toString ( ) , 7 ) ) ) ; } else { System . out . println ( "Invalid selection: " + ( pos + 1 ) ) ; } }
Rent a car available in the last serach result
23,517
public void addProperty ( String name , String ... values ) { List < String > valueList = new ArrayList < String > ( ) ; for ( String value : values ) { valueList . add ( value . trim ( ) ) ; } properties . put ( name . trim ( ) , valueList ) ; }
Add a property with the given name and the given list of values to this Properties object . Name and values are trimmed before the property is added .
23,518
protected SingleBusLocatorRegistrar getRegistrar ( Bus bus ) { SingleBusLocatorRegistrar registrar = busRegistrars . get ( bus ) ; if ( registrar == null ) { check ( locatorClient , "serviceLocator" , "registerService" ) ; registrar = new SingleBusLocatorRegistrar ( bus ) ; registrar . setServiceLocator ( locatorClient ) ; registrar . setEndpointPrefix ( endpointPrefix ) ; Map < String , String > endpointPrefixes = new HashMap < String , String > ( ) ; endpointPrefixes . put ( "HTTP" , endpointPrefixHttp ) ; endpointPrefixes . put ( "HTTPS" , endpointPrefixHttps ) ; registrar . setEndpointPrefixes ( endpointPrefixes ) ; busRegistrars . put ( bus , registrar ) ; addLifeCycleListener ( bus ) ; } return registrar ; }
Retrieves the registar linked to the bus . Creates a new registar is not present .
23,519
public void useXopAttachmentServiceWithWebClient ( ) throws Exception { final String serviceURI = "http://localhost:" + port + "/services/attachments/xop" ; JAXRSClientFactoryBean factoryBean = new JAXRSClientFactoryBean ( ) ; factoryBean . setAddress ( serviceURI ) ; factoryBean . setProperties ( Collections . singletonMap ( org . apache . cxf . message . Message . MTOM_ENABLED , ( Object ) "true" ) ) ; WebClient client = factoryBean . createWebClient ( ) ; WebClient . getConfig ( client ) . getRequestContext ( ) . put ( "support.type.as.multipart" , "true" ) ; client . type ( "multipart/related" ) . accept ( "multipart/related" ) ; XopBean xop = createXopBean ( ) ; System . out . println ( ) ; System . out . println ( "Posting a XOP attachment with a WebClient" ) ; XopBean xopResponse = client . post ( xop , XopBean . class ) ; verifyXopResponse ( xop , xopResponse ) ; }
Writes and reads the XOP attachment using a CXF JAX - RS WebClient . Note that WebClient is created with the help of JAXRSClientFactoryBean . JAXRSClientFactoryBean can be used when neither of the WebClient factory methods is appropriate . For example in this case an mtom - enabled property is set on the factory bean first .
23,520
public void useXopAttachmentServiceWithProxy ( ) throws Exception { final String serviceURI = "http://localhost:" + port + "/services/attachments" ; XopAttachmentService proxy = JAXRSClientFactory . create ( serviceURI , XopAttachmentService . class ) ; XopBean xop = createXopBean ( ) ; System . out . println ( ) ; System . out . println ( "Posting a XOP attachment with a proxy" ) ; XopBean xopResponse = proxy . echoXopAttachment ( xop ) ; verifyXopResponse ( xop , xopResponse ) ; }
Writes and reads the XOP attachment using a CXF JAX - RS Proxy The proxy automatically sets the mtom - enabled property by checking the CXF EndpointProperty set on the XopAttachment interface .
23,521
private XopBean createXopBean ( ) throws Exception { XopBean xop = new XopBean ( ) ; xop . setName ( "xopName" ) ; InputStream is = getClass ( ) . getResourceAsStream ( "/java.jpg" ) ; byte [ ] data = IOUtils . readBytesFromStream ( is ) ; xop . setBytes ( data ) ; xop . setDatahandler ( new DataHandler ( new ByteArrayDataSource ( data , "application/octet-stream" ) ) ) ; if ( Boolean . getBoolean ( "java.awt.headless" ) ) { System . out . println ( "Running headless. Ignoring an Image property." ) ; } else { xop . setImage ( getImage ( "/java.jpg" ) ) ; } return xop ; }
Creates a XopBean . The image on the disk is included as a byte array a DataHandler and java . awt . Image
23,522
private void verifyXopResponse ( XopBean xopOriginal , XopBean xopResponse ) { if ( ! Arrays . equals ( xopResponse . getBytes ( ) , xopOriginal . getBytes ( ) ) ) { throw new RuntimeException ( "Received XOP attachment is corrupted" ) ; } System . out . println ( ) ; System . out . println ( "XOP attachment has been successfully received" ) ; }
Verifies that the received image is identical to the original one .
23,523
public void setMonitoringService ( org . talend . esb . sam . common . service . MonitoringService monitoringService ) { this . monitoringService = monitoringService ; }
Sets the monitoring service .
23,524
private static void throwFault ( String code , String message , Throwable t ) throws PutEventsFault { if ( LOG . isLoggable ( Level . SEVERE ) ) { LOG . log ( Level . SEVERE , "Throw Fault " + code + " " + message , t ) ; } FaultType faultType = new FaultType ( ) ; faultType . setFaultCode ( code ) ; faultType . setFaultMessage ( message ) ; StringWriter stringWriter = new StringWriter ( ) ; PrintWriter printWriter = new PrintWriter ( stringWriter ) ; t . printStackTrace ( printWriter ) ; faultType . setStackTrace ( stringWriter . toString ( ) ) ; throw new PutEventsFault ( message , faultType , t ) ; }
Throw fault .
23,525
public void putEvents ( List < Event > events ) { Exception lastException ; List < EventType > eventTypes = new ArrayList < EventType > ( ) ; for ( Event event : events ) { EventType eventType = EventMapper . map ( event ) ; eventTypes . add ( eventType ) ; } int i = 0 ; lastException = null ; while ( i < numberOfRetries ) { try { monitoringService . putEvents ( eventTypes ) ; break ; } catch ( Exception e ) { lastException = e ; i ++ ; } if ( i < numberOfRetries ) { try { Thread . sleep ( delayBetweenRetry ) ; } catch ( InterruptedException e ) { break ; } } } if ( i == numberOfRetries ) { throw new MonitoringException ( "1104" , "Could not send events to monitoring service after " + numberOfRetries + " retries." , lastException , events ) ; } }
Sends all events to the web service . Events will be transformed with mapper before sending .
23,526
private EventType createEventType ( EventEnumType type ) { EventType eventType = new EventType ( ) ; eventType . setTimestamp ( Converter . convertDate ( new Date ( ) ) ) ; eventType . setEventType ( type ) ; OriginatorType origType = new OriginatorType ( ) ; origType . setProcessId ( Converter . getPID ( ) ) ; try { InetAddress inetAddress = InetAddress . getLocalHost ( ) ; origType . setIp ( inetAddress . getHostAddress ( ) ) ; origType . setHostname ( inetAddress . getHostName ( ) ) ; } catch ( UnknownHostException e ) { origType . setHostname ( "Unknown hostname" ) ; origType . setIp ( "Unknown ip address" ) ; } eventType . setOriginator ( origType ) ; String path = System . getProperty ( "karaf.home" ) ; CustomInfoType ciType = new CustomInfoType ( ) ; CustomInfoType . Item cItem = new CustomInfoType . Item ( ) ; cItem . setKey ( "path" ) ; cItem . setValue ( path ) ; ciType . getItem ( ) . add ( cItem ) ; eventType . setCustomInfo ( ciType ) ; return eventType ; }
Creates the event type .
23,527
private void putEvent ( EventType eventType ) throws Exception { List < EventType > eventTypes = Collections . singletonList ( eventType ) ; int i ; for ( i = 0 ; i < retryNum ; ++ i ) { try { monitoringService . putEvents ( eventTypes ) ; break ; } catch ( Exception e ) { LOG . log ( Level . SEVERE , e . getMessage ( ) , e ) ; } Thread . sleep ( retryDelay ) ; } if ( i == retryNum ) { LOG . warning ( "Could not send events to monitoring service after " + retryNum + " retries." ) ; throw new Exception ( "Send SERVER_START/SERVER_STOP event to SAM Server failed" ) ; } }
Put event .
23,528
private boolean checkConfig ( BundleContext context ) throws Exception { ServiceReference serviceRef = context . getServiceReference ( ConfigurationAdmin . class . getName ( ) ) ; ConfigurationAdmin cfgAdmin = ( ConfigurationAdmin ) context . getService ( serviceRef ) ; Configuration config = cfgAdmin . getConfiguration ( "org.talend.esb.sam.agent" ) ; return "true" . equalsIgnoreCase ( ( String ) config . getProperties ( ) . get ( "collector.lifecycleEvent" ) ) ; }
Check config .
23,529
private void initWsClient ( BundleContext context ) throws Exception { ServiceReference serviceRef = context . getServiceReference ( ConfigurationAdmin . class . getName ( ) ) ; ConfigurationAdmin cfgAdmin = ( ConfigurationAdmin ) context . getService ( serviceRef ) ; Configuration config = cfgAdmin . getConfiguration ( "org.talend.esb.sam.agent" ) ; String serviceURL = ( String ) config . getProperties ( ) . get ( "service.url" ) ; retryNum = Integer . parseInt ( ( String ) config . getProperties ( ) . get ( "service.retry.number" ) ) ; retryDelay = Long . parseLong ( ( String ) config . getProperties ( ) . get ( "service.retry.delay" ) ) ; JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean ( ) ; factory . setServiceClass ( org . talend . esb . sam . monitoringservice . v1 . MonitoringService . class ) ; factory . setAddress ( serviceURL ) ; monitoringService = ( MonitoringService ) factory . create ( ) ; }
Inits the ws client .
23,530
protected void handleResponseOut ( T message ) throws Fault { Message reqMsg = message . getExchange ( ) . getInMessage ( ) ; if ( reqMsg == null ) { LOG . warning ( "InMessage is null!" ) ; return ; } Exchange ex = reqMsg . getExchange ( ) ; if ( ex . isOneWay ( ) ) { return ; } String reqFid = FlowIdHelper . getFlowId ( reqMsg ) ; if ( reqFid == null ) { if ( LOG . isLoggable ( Level . FINE ) ) { LOG . fine ( "Some interceptor throws fault.Setting FlowId in response." ) ; } reqFid = FlowIdProtocolHeaderCodec . readFlowId ( message ) ; } if ( reqFid == null ) { Message inMsg = ex . getInMessage ( ) ; reqFid = FlowIdProtocolHeaderCodec . readFlowId ( inMsg ) ; if ( null != reqFid ) { if ( LOG . isLoggable ( Level . FINE ) ) { LOG . fine ( "FlowId '" + reqFid + "' found in message of fault incoming exchange." ) ; LOG . fine ( "Calling EventProducerInterceptor to log IN message" ) ; } handleINEvent ( ex , reqFid ) ; } } if ( reqFid == null ) { reqFid = FlowIdSoapCodec . readFlowId ( message ) ; } if ( reqFid != null ) { if ( LOG . isLoggable ( Level . FINE ) ) { LOG . fine ( "FlowId '" + reqFid + "' found in incoming message." ) ; } } else { reqFid = ContextUtils . generateUUID ( ) ; if ( null != ex . getOutFaultMessage ( ) ) { if ( LOG . isLoggable ( Level . FINE ) ) { LOG . fine ( "FlowId '" + reqFid + "' generated for fault message." ) ; LOG . fine ( "Calling EventProducerInterceptor to log IN message" ) ; } handleINEvent ( ex , reqFid ) ; } if ( LOG . isLoggable ( Level . FINE ) ) { LOG . fine ( "No flowId found in incoming message! Generate new flowId " + reqFid ) ; } } FlowIdHelper . setFlowId ( message , reqFid ) ; }
Handling out responce .
23,531
protected void handleRequestOut ( T message ) throws Fault { String flowId = FlowIdHelper . getFlowId ( message ) ; if ( flowId == null && message . containsKey ( PhaseInterceptorChain . PREVIOUS_MESSAGE ) ) { @ SuppressWarnings ( "unchecked" ) WeakReference < Message > wrPreviousMessage = ( WeakReference < Message > ) message . get ( PhaseInterceptorChain . PREVIOUS_MESSAGE ) ; Message previousMessage = ( Message ) wrPreviousMessage . get ( ) ; flowId = FlowIdHelper . getFlowId ( previousMessage ) ; if ( flowId != null && LOG . isLoggable ( Level . FINE ) ) { LOG . fine ( "flowId '" + flowId + "' found in previous message" ) ; } } if ( flowId == null ) { flowId = ContextUtils . generateUUID ( ) ; if ( LOG . isLoggable ( Level . FINE ) ) { LOG . fine ( "Generate new flowId '" + flowId + "'" ) ; } } FlowIdHelper . setFlowId ( message , flowId ) ; }
Handling out request .
23,532
protected void handleINEvent ( Exchange exchange , String reqFid ) throws Fault { Message inMsg = exchange . getInMessage ( ) ; EventProducerInterceptor epi = null ; FlowIdHelper . setFlowId ( inMsg , reqFid ) ; ListIterator < Interceptor < ? extends Message > > interceptors = inMsg . getInterceptorChain ( ) . getIterator ( ) ; while ( interceptors . hasNext ( ) && epi == null ) { Interceptor < ? extends Message > interceptor = interceptors . next ( ) ; if ( interceptor instanceof EventProducerInterceptor ) { epi = ( EventProducerInterceptor ) interceptor ; epi . handleMessage ( inMsg ) ; } } }
Calling EventProducerInterceptor in case of logging faults .
23,533
public void setDialect ( String dialect ) { String [ ] scripts = createScripts . get ( dialect ) ; createSql = scripts [ 0 ] ; createSqlInd = scripts [ 1 ] ; }
Sets the database dialect .
23,534
public static Event map ( EventType eventType ) { Event event = new Event ( ) ; event . setEventType ( mapEventTypeEnum ( eventType . getEventType ( ) ) ) ; Date date = ( eventType . getTimestamp ( ) == null ) ? new Date ( ) : eventType . getTimestamp ( ) . toGregorianCalendar ( ) . getTime ( ) ; event . setTimestamp ( date ) ; event . setOriginator ( mapOriginatorType ( eventType . getOriginator ( ) ) ) ; MessageInfo messageInfo = mapMessageInfo ( eventType . getMessageInfo ( ) ) ; event . setMessageInfo ( messageInfo ) ; String content = mapContent ( eventType . getContent ( ) ) ; event . setContent ( content ) ; event . getCustomInfo ( ) . clear ( ) ; event . getCustomInfo ( ) . putAll ( mapCustomInfo ( eventType . getCustomInfo ( ) ) ) ; return event ; }
Map the EventType .
23,535
private static Map < String , String > mapCustomInfo ( CustomInfoType ciType ) { Map < String , String > customInfo = new HashMap < String , String > ( ) ; if ( ciType != null ) { for ( CustomInfoType . Item item : ciType . getItem ( ) ) { customInfo . put ( item . getKey ( ) , item . getValue ( ) ) ; } } return customInfo ; }
Map custom info .
23,536
private static String mapContent ( DataHandler dh ) { if ( dh == null ) { return "" ; } try { InputStream is = dh . getInputStream ( ) ; String content = IOUtils . toString ( is ) ; is . close ( ) ; return content ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } }
Map content .
23,537
private static MessageInfo mapMessageInfo ( MessageInfoType messageInfoType ) { MessageInfo messageInfo = new MessageInfo ( ) ; if ( messageInfoType != null ) { messageInfo . setFlowId ( messageInfoType . getFlowId ( ) ) ; messageInfo . setMessageId ( messageInfoType . getMessageId ( ) ) ; messageInfo . setOperationName ( messageInfoType . getOperationName ( ) ) ; messageInfo . setPortType ( messageInfoType . getPorttype ( ) == null ? "" : messageInfoType . getPorttype ( ) . toString ( ) ) ; messageInfo . setTransportType ( messageInfoType . getTransport ( ) ) ; } return messageInfo ; }
Map message info .
23,538
private static Originator mapOriginatorType ( OriginatorType originatorType ) { Originator originator = new Originator ( ) ; if ( originatorType != null ) { originator . setCustomId ( originatorType . getCustomId ( ) ) ; originator . setHostname ( originatorType . getHostname ( ) ) ; originator . setIp ( originatorType . getIp ( ) ) ; originator . setProcessId ( originatorType . getProcessId ( ) ) ; originator . setPrincipal ( originatorType . getPrincipal ( ) ) ; } return originator ; }
Map originator type .
23,539
private static EventTypeEnum mapEventTypeEnum ( EventEnumType eventType ) { if ( eventType != null ) { return EventTypeEnum . valueOf ( eventType . name ( ) ) ; } return EventTypeEnum . UNKNOWN ; }
Map event type enum .
23,540
public void useNewSOAPService ( boolean direct ) throws Exception { URL wsdlURL = getClass ( ) . getResource ( "/CustomerServiceNew.wsdl" ) ; org . customer . service . CustomerServiceService service = new org . customer . service . CustomerServiceService ( wsdlURL ) ; org . customer . service . CustomerService customerService = direct ? service . getCustomerServicePort ( ) : service . getCustomerServiceNewPort ( ) ; System . out . println ( "Using new SOAP CustomerService with new client" ) ; customer . v2 . Customer customer = createNewCustomer ( "Barry New SOAP" ) ; customerService . updateCustomer ( customer ) ; customer = customerService . getCustomerByName ( "Barry New SOAP" ) ; printNewCustomerDetails ( customer ) ; }
New SOAP client uses new SOAP service .
23,541
public void useNewSOAPServiceWithOldClient ( ) throws Exception { URL wsdlURL = getClass ( ) . getResource ( "/CustomerServiceNew.wsdl" ) ; com . example . customerservice . CustomerServiceService service = new com . example . customerservice . CustomerServiceService ( wsdlURL ) ; com . example . customerservice . CustomerService customerService = service . getCustomerServicePort ( ) ; Client client = ClientProxy . getClient ( customerService ) ; addTransformInterceptors ( client . getInInterceptors ( ) , client . getOutInterceptors ( ) , false ) ; System . out . println ( "Using new SOAP CustomerService with old client" ) ; customer . v1 . Customer customer = createOldCustomer ( "Barry Old to New SOAP" ) ; customerService . updateCustomer ( customer ) ; customer = customerService . getCustomerByName ( "Barry Old to New SOAP" ) ; printOldCustomerDetails ( customer ) ; }
Old SOAP client uses new SOAP service
23,542
public void useNewSOAPServiceWithOldClientAndRedirection ( ) throws Exception { URL wsdlURL = getClass ( ) . getResource ( "/CustomerService.wsdl" ) ; com . example . customerservice . CustomerServiceService service = new com . example . customerservice . CustomerServiceService ( wsdlURL ) ; com . example . customerservice . CustomerService customerService = service . getCustomerServiceRedirectPort ( ) ; System . out . println ( "Using new SOAP CustomerService with old client and the redirection" ) ; customer . v1 . Customer customer = createOldCustomer ( "Barry Old to New SOAP With Redirection" ) ; customerService . updateCustomer ( customer ) ; customer = customerService . getCustomerByName ( "Barry Old to New SOAP With Redirection" ) ; printOldCustomerDetails ( customer ) ; }
Old SOAP client uses new SOAP service with the redirection to the new endpoint and transformation on the server side
23,543
private void addTransformInterceptors ( List < Interceptor < ? > > inInterceptors , List < Interceptor < ? > > outInterceptors , boolean newClient ) { Map < String , String > newToOldTransformMap = new HashMap < String , String > ( ) ; newToOldTransformMap . put ( "{http://customer/v2}*" , "{http://customer/v1}*" ) ; Map < String , String > oldToNewTransformMap = Collections . singletonMap ( "{http://customer/v1}*" , "{http://customer/v2}*" ) ; TransformOutInterceptor outTransform = new TransformOutInterceptor ( ) ; outTransform . setOutTransformElements ( newClient ? newToOldTransformMap : oldToNewTransformMap ) ; if ( newClient ) { newToOldTransformMap . put ( "{http://customer/v2}briefDescription" , "" ) ; } TransformInInterceptor inTransform = new TransformInInterceptor ( ) ; inTransform . setInTransformElements ( newClient ? oldToNewTransformMap : newToOldTransformMap ) ; inInterceptors . add ( inTransform ) ; outInterceptors . add ( outTransform ) ; }
Prepares transformation interceptors for a client .
23,544
@ SuppressWarnings ( "unused" ) @ XmlAttribute ( name = "id" ) private String getXmlID ( ) { return String . format ( "%s-%s" , this . getClass ( ) . getSimpleName ( ) , Long . valueOf ( id ) ) ; }
to do with XmlId value being strictly of type String
23,545
private void stopAllServersAndRemoveCamelContext ( CamelContext camelContext ) { log . debug ( "Stopping all servers associated with {}" , camelContext ) ; List < SingleBusLocatorRegistrar > registrars = locatorRegistrar . getAllRegistars ( camelContext ) ; registrars . forEach ( registrar -> registrar . stopAllServersAndRemoveCamelContext ( ) ) ; }
Stops all servers linked with the current camel context
23,546
public static EventType map ( Event event ) { EventType eventType = new EventType ( ) ; eventType . setTimestamp ( Converter . convertDate ( event . getTimestamp ( ) ) ) ; eventType . setEventType ( convertEventType ( event . getEventType ( ) ) ) ; OriginatorType origType = mapOriginator ( event . getOriginator ( ) ) ; eventType . setOriginator ( origType ) ; MessageInfoType miType = mapMessageInfo ( event . getMessageInfo ( ) ) ; eventType . setMessageInfo ( miType ) ; eventType . setCustomInfo ( convertCustomInfo ( event . getCustomInfo ( ) ) ) ; eventType . setContentCut ( event . isContentCut ( ) ) ; if ( event . getContent ( ) != null ) { DataHandler datHandler = getDataHandlerForString ( event ) ; eventType . setContent ( datHandler ) ; } return eventType ; }
convert Event bean to EventType manually .
23,547
private static DataHandler getDataHandlerForString ( Event event ) { try { return new DataHandler ( new ByteDataSource ( event . getContent ( ) . getBytes ( "UTF-8" ) ) ) ; } catch ( UnsupportedEncodingException e ) { throw new RuntimeException ( e ) ; } }
Gets the data handler from event .
23,548
private static MessageInfoType mapMessageInfo ( MessageInfo messageInfo ) { if ( messageInfo == null ) { return null ; } MessageInfoType miType = new MessageInfoType ( ) ; miType . setMessageId ( messageInfo . getMessageId ( ) ) ; miType . setFlowId ( messageInfo . getFlowId ( ) ) ; miType . setPorttype ( convertString ( messageInfo . getPortType ( ) ) ) ; miType . setOperationName ( messageInfo . getOperationName ( ) ) ; miType . setTransport ( messageInfo . getTransportType ( ) ) ; return miType ; }
Mapping message info .
23,549
private static OriginatorType mapOriginator ( Originator originator ) { if ( originator == null ) { return null ; } OriginatorType origType = new OriginatorType ( ) ; origType . setProcessId ( originator . getProcessId ( ) ) ; origType . setIp ( originator . getIp ( ) ) ; origType . setHostname ( originator . getHostname ( ) ) ; origType . setCustomId ( originator . getCustomId ( ) ) ; origType . setPrincipal ( originator . getPrincipal ( ) ) ; return origType ; }
Mapping originator .
23,550
private static CustomInfoType convertCustomInfo ( Map < String , String > customInfo ) { if ( customInfo == null ) { return null ; } CustomInfoType ciType = new CustomInfoType ( ) ; for ( Entry < String , String > entry : customInfo . entrySet ( ) ) { CustomInfoType . Item cItem = new CustomInfoType . Item ( ) ; cItem . setKey ( entry . getKey ( ) ) ; cItem . setValue ( entry . getValue ( ) ) ; ciType . getItem ( ) . add ( cItem ) ; } return ciType ; }
Convert custom info .
23,551
private static EventEnumType convertEventType ( org . talend . esb . sam . common . event . EventTypeEnum eventType ) { if ( eventType == null ) { return null ; } return EventEnumType . valueOf ( eventType . name ( ) ) ; }
Convert event type .
23,552
private static QName convertString ( String str ) { if ( str != null ) { return QName . valueOf ( str ) ; } else { return null ; } }
Convert string to qname .
23,553
public void logException ( Level level ) { if ( ! LOG . isLoggable ( level ) ) { return ; } final StringBuilder builder = new StringBuilder ( ) ; builder . append ( "\n----------------------------------------------------" ) ; builder . append ( "\nMonitoringException" ) ; builder . append ( "\n----------------------------------------------------" ) ; builder . append ( "\nCode: " ) . append ( code ) ; builder . append ( "\nMessage: " ) . append ( message ) ; builder . append ( "\n----------------------------------------------------" ) ; if ( events != null ) { for ( Event event : events ) { builder . append ( "\nEvent:" ) ; if ( event . getMessageInfo ( ) != null ) { builder . append ( "\nMessage id: " ) . append ( event . getMessageInfo ( ) . getMessageId ( ) ) ; builder . append ( "\nFlow id: " ) . append ( event . getMessageInfo ( ) . getFlowId ( ) ) ; builder . append ( "\n----------------------------------------------------" ) ; } else { builder . append ( "\nNo message id and no flow id" ) ; } } } builder . append ( "\n----------------------------------------------------\n" ) ; LOG . log ( level , builder . toString ( ) , this ) ; }
Prints the error message as log message .
23,554
private LocatorSelectionStrategy getLocatorSelectionStrategy ( String locatorSelectionStrategy ) { if ( null == locatorSelectionStrategy ) { return locatorSelectionStrategyMap . get ( DEFAULT_STRATEGY ) . getInstance ( ) ; } if ( LOG . isLoggable ( Level . FINE ) ) { LOG . log ( Level . FINE , "Strategy " + locatorSelectionStrategy + " was set for LocatorClientRegistrar." ) ; } if ( locatorSelectionStrategyMap . containsKey ( locatorSelectionStrategy ) ) { return locatorSelectionStrategyMap . get ( locatorSelectionStrategy ) . getInstance ( ) ; } else { if ( LOG . isLoggable ( Level . WARNING ) ) { LOG . log ( Level . WARNING , "LocatorSelectionStrategy " + locatorSelectionStrategy + " not registered at LocatorClientEnabler." ) ; } return locatorSelectionStrategyMap . get ( DEFAULT_STRATEGY ) . getInstance ( ) ; } }
If the String argument locatorSelectionStrategy is as key in the map representing the locatorSelectionStrategies the corresponding strategy is selected else it remains unchanged .
23,555
@ Value ( "${locator.strategy}" ) public void setDefaultLocatorSelectionStrategy ( String defaultLocatorSelectionStrategy ) { this . defaultLocatorSelectionStrategy = defaultLocatorSelectionStrategy ; if ( LOG . isLoggable ( Level . FINE ) ) { LOG . log ( Level . FINE , "Default strategy " + defaultLocatorSelectionStrategy + " was set for LocatorClientRegistrar." ) ; } }
If the String argument defaultLocatorSelectionStrategy is as key in the map representing the locatorSelectionStrategies the corresponding strategy is selected and set as default strategy else both the selected strategy and the default strategy remain unchanged .
23,556
public void enable ( ConduitSelectorHolder conduitSelectorHolder , SLPropertiesMatcher matcher , String selectionStrategy ) { LocatorTargetSelector selector = new LocatorTargetSelector ( ) ; selector . setEndpoint ( conduitSelectorHolder . getConduitSelector ( ) . getEndpoint ( ) ) ; String actualStrategy = selectionStrategy != null ? selectionStrategy : defaultLocatorSelectionStrategy ; LocatorSelectionStrategy locatorSelectionStrategy = getLocatorSelectionStrategy ( actualStrategy ) ; locatorSelectionStrategy . setServiceLocator ( locatorClient ) ; if ( matcher != null ) { locatorSelectionStrategy . setMatcher ( matcher ) ; } selector . setLocatorSelectionStrategy ( locatorSelectionStrategy ) ; if ( LOG . isLoggable ( Level . INFO ) ) { LOG . log ( Level . INFO , "Client enabled with strategy " + locatorSelectionStrategy . getClass ( ) . getName ( ) + "." ) ; } conduitSelectorHolder . setConduitSelector ( selector ) ; if ( LOG . isLoggable ( Level . FINE ) ) { LOG . log ( Level . FINE , "Successfully enabled client " + conduitSelectorHolder + " for the service locator" ) ; } }
The selectionStrategy given as String argument is selected as locatorSelectionStrategy . If selectionStrategy is null the defaultLocatorSelectionStrategy is used instead . Then the new locatorSelectionStrategy is connected to the locatorClient and the matcher . A new LocatorTargetSelector is created set to the locatorSelectionStrategy and then set as selector in the conduitSelectorHolder .
23,557
public static void applyWsdlExtensions ( Bus bus ) { ExtensionRegistry registry = bus . getExtension ( WSDLManager . class ) . getExtensionRegistry ( ) ; try { JAXBExtensionHelper . addExtensions ( registry , javax . wsdl . Definition . class , org . talend . esb . mep . requestcallback . impl . wsdl . PLType . class ) ; JAXBExtensionHelper . addExtensions ( registry , javax . wsdl . Binding . class , org . talend . esb . mep . requestcallback . impl . wsdl . CallbackExtension . class ) ; } catch ( JAXBException e ) { throw new RuntimeException ( "Failed to add WSDL JAXB extensions" , e ) ; } }
Adds JAXB WSDL extensions to allow work with custom WSDL elements such as \ partner - link \
23,558
public void setQueue ( EventQueue queue ) { if ( epi == null ) { MessageToEventMapper mapper = new MessageToEventMapper ( ) ; mapper . setMaxContentLength ( maxContentLength ) ; epi = new EventProducerInterceptor ( mapper , queue ) ; } }
Sets the queue .
23,559
private boolean detectWSAddressingFeature ( InterceptorProvider provider , Bus bus ) { if ( bus . getFeatures ( ) != null ) { Iterator < Feature > busFeatures = bus . getFeatures ( ) . iterator ( ) ; while ( busFeatures . hasNext ( ) ) { Feature busFeature = busFeatures . next ( ) ; if ( busFeature instanceof WSAddressingFeature ) { return true ; } } } Iterator < Interceptor < ? extends Message > > interceptors = provider . getInInterceptors ( ) . iterator ( ) ; while ( interceptors . hasNext ( ) ) { Interceptor < ? extends Message > ic = interceptors . next ( ) ; if ( ic instanceof MAPAggregator ) { return true ; } } return false ; }
detect if WS Addressing feature already enabled .
23,560
private void addWSAddressingInterceptors ( InterceptorProvider provider ) { MAPAggregator mapAggregator = new MAPAggregator ( ) ; MAPCodec mapCodec = new MAPCodec ( ) ; provider . getInInterceptors ( ) . add ( mapAggregator ) ; provider . getInInterceptors ( ) . add ( mapCodec ) ; provider . getOutInterceptors ( ) . add ( mapAggregator ) ; provider . getOutInterceptors ( ) . add ( mapCodec ) ; provider . getInFaultInterceptors ( ) . add ( mapAggregator ) ; provider . getInFaultInterceptors ( ) . add ( mapCodec ) ; provider . getOutFaultInterceptors ( ) . add ( mapAggregator ) ; provider . getOutFaultInterceptors ( ) . add ( mapCodec ) ; }
Add WSAddressing Interceptors to InterceptorProvider in order to using AddressingProperties to get MessageID .
23,561
public static String readFlowId ( Message message ) { if ( ! ( message instanceof SoapMessage ) ) { return null ; } String flowId = null ; Header hdFlowId = ( ( SoapMessage ) message ) . getHeader ( FLOW_ID_QNAME ) ; if ( hdFlowId != null ) { if ( hdFlowId . getObject ( ) instanceof String ) { flowId = ( String ) hdFlowId . getObject ( ) ; } else if ( hdFlowId . getObject ( ) instanceof Node ) { Node headerNode = ( Node ) hdFlowId . getObject ( ) ; flowId = headerNode . getTextContent ( ) ; } else { LOG . warning ( "Found FlowId soap header but value is not a String or a Node! Value: " + hdFlowId . getObject ( ) . toString ( ) ) ; } } return flowId ; }
Read flow id .
23,562
public static void writeFlowId ( Message message , String flowId ) { if ( ! ( message instanceof SoapMessage ) ) { return ; } SoapMessage soapMessage = ( SoapMessage ) message ; Header hdFlowId = soapMessage . getHeader ( FLOW_ID_QNAME ) ; if ( hdFlowId != null ) { LOG . warning ( "FlowId already existing in soap header, need not to write FlowId header." ) ; return ; } try { soapMessage . getHeaders ( ) . add ( new Header ( FLOW_ID_QNAME , flowId , new JAXBDataBinding ( String . class ) ) ) ; if ( LOG . isLoggable ( Level . FINE ) ) { LOG . fine ( "Stored flowId '" + flowId + "' in soap header: " + FLOW_ID_QNAME ) ; } } catch ( JAXBException e ) { LOG . log ( Level . SEVERE , "Couldn't create flowId header." , e ) ; } }
Write flow id to message .
23,563
public static STSClient createSTSX509Client ( Bus bus , Map < String , String > stsProps ) { final STSClient stsClient = createClient ( bus , stsProps ) ; stsClient . setWsdlLocation ( stsProps . get ( STS_X509_WSDL_LOCATION ) ) ; stsClient . setEndpointQName ( new QName ( stsProps . get ( STS_NAMESPACE ) , stsProps . get ( STS_X509_ENDPOINT_NAME ) ) ) ; return stsClient ; }
for bpm connector
23,564
private boolean isSecuredByPolicy ( Server server ) { boolean isSecured = false ; EndpointInfo ei = server . getEndpoint ( ) . getEndpointInfo ( ) ; PolicyEngine pe = bus . getExtension ( PolicyEngine . class ) ; if ( null == pe ) { LOG . finest ( "No Policy engine found" ) ; return isSecured ; } Destination destination = server . getDestination ( ) ; EndpointPolicy ep = pe . getServerEndpointPolicy ( ei , destination , null ) ; Collection < Assertion > assertions = ep . getChosenAlternative ( ) ; for ( Assertion a : assertions ) { if ( a instanceof TransportBinding ) { TransportBinding tb = ( TransportBinding ) a ; TransportToken tt = tb . getTransportToken ( ) ; AbstractToken t = tt . getToken ( ) ; if ( t instanceof HttpsToken ) { isSecured = true ; break ; } } } Policy policy = ep . getPolicy ( ) ; List < PolicyComponent > pcList = policy . getPolicyComponents ( ) ; for ( PolicyComponent a : pcList ) { if ( a instanceof TransportBinding ) { TransportBinding tb = ( TransportBinding ) a ; TransportToken tt = tb . getTransportToken ( ) ; AbstractToken t = tt . getToken ( ) ; if ( t instanceof HttpsToken ) { isSecured = true ; break ; } } } return isSecured ; }
Is the transport secured by a policy
23,565
private boolean isSecuredByProperty ( Server server ) { boolean isSecured = false ; Object value = server . getEndpoint ( ) . get ( "org.talend.tesb.endpoint.secured" ) ; if ( value instanceof String ) { try { isSecured = Boolean . valueOf ( ( String ) value ) ; } catch ( Exception ex ) { } } return isSecured ; }
Is the transport secured by a JAX - WS property
23,566
private void writeCustomInfo ( Event event ) { for ( Map . Entry < String , String > customInfo : event . getCustomInfo ( ) . entrySet ( ) ) { long cust_id = dbDialect . getIncrementer ( ) . nextLongValue ( ) ; getJdbcTemplate ( ) . update ( "insert into EVENTS_CUSTOMINFO (ID, EVENT_ID, CUST_KEY, CUST_VALUE)" + " values (?,?,?,?)" , cust_id , event . getPersistedId ( ) , customInfo . getKey ( ) , customInfo . getValue ( ) ) ; } }
write CustomInfo list into table .
23,567
private Map < String , String > readCustomInfo ( long eventId ) { List < Map < String , Object > > rows = getJdbcTemplate ( ) . queryForList ( "select * from EVENTS_CUSTOMINFO where EVENT_ID=" + eventId ) ; Map < String , String > customInfo = new HashMap < String , String > ( rows . size ( ) ) ; for ( Map < String , Object > row : rows ) { customInfo . put ( ( String ) row . get ( "CUST_KEY" ) , ( String ) row . get ( "CUST_VALUE" ) ) ; } return customInfo ; }
read CustomInfo list from table .
23,568
private String toSQLPattern ( String attribute ) { String pattern = attribute . replace ( "*" , "%" ) ; if ( ! pattern . startsWith ( "%" ) ) { pattern = "%" + pattern ; } if ( ! pattern . endsWith ( "%" ) ) { pattern = pattern . concat ( "%" ) ; } return pattern ; }
To sql pattern .
23,569
private void checkMessageID ( Message message ) { if ( ! MessageUtils . isOutbound ( message ) ) return ; AddressingProperties maps = ContextUtils . retrieveMAPs ( message , false , MessageUtils . isOutbound ( message ) ) ; if ( maps == null ) { maps = new AddressingProperties ( ) ; } if ( maps . getMessageID ( ) == null ) { String messageID = ContextUtils . generateUUID ( ) ; boolean isRequestor = ContextUtils . isRequestor ( message ) ; maps . setMessageID ( ContextUtils . getAttributedURI ( messageID ) ) ; ContextUtils . storeMAPs ( maps , message , ContextUtils . isOutbound ( message ) , isRequestor ) ; } }
check if MessageID exists in the message if not only generate new MessageID for outbound message .
23,570
public static String getCorrelationId ( Message message ) { String correlationId = ( String ) message . get ( CORRELATION_ID_KEY ) ; if ( null == correlationId ) { correlationId = readCorrelationId ( message ) ; } if ( null == correlationId ) { correlationId = readCorrelationIdSoap ( message ) ; } return correlationId ; }
Get CorrelationId from message .
23,571
public static String readCorrelationId ( Message message ) { String correlationId = null ; Map < String , List < String > > headers = getOrCreateProtocolHeader ( message ) ; List < String > correlationIds = headers . get ( CORRELATION_ID_KEY ) ; if ( correlationIds != null && correlationIds . size ( ) > 0 ) { correlationId = correlationIds . get ( 0 ) ; if ( LOG . isLoggable ( Level . FINE ) ) { LOG . fine ( "HTTP header '" + CORRELATION_ID_KEY + "' found: " + correlationId ) ; } } else { if ( LOG . isLoggable ( Level . FINE ) ) { LOG . fine ( "No HTTP header '" + CORRELATION_ID_KEY + "' found" ) ; } } return correlationId ; }
Read correlation id from message .
23,572
private static Map < String , List < String > > getOrCreateProtocolHeader ( Message message ) { Map < String , List < String > > headers = CastUtils . cast ( ( Map < ? , ? > ) message . get ( Message . PROTOCOL_HEADERS ) ) ; if ( headers == null ) { headers = new HashMap < String , List < String > > ( ) ; message . put ( Message . PROTOCOL_HEADERS , headers ) ; } return headers ; }
Gets the or create protocol header .
23,573
public void putEvents ( List < Event > events ) { List < Event > filteredEvents = filterEvents ( events ) ; executeHandlers ( filteredEvents ) ; for ( Event event : filteredEvents ) { persistenceHandler . writeEvent ( event ) ; } }
Executes all event manipulating handler and writes the event with persist handler .
23,574
private List < Event > filterEvents ( List < Event > events ) { List < Event > filteredEvents = new ArrayList < Event > ( ) ; for ( Event event : events ) { if ( ! filter ( event ) ) { filteredEvents . add ( event ) ; } } return filteredEvents ; }
Filter events .
23,575
public boolean filter ( Event event ) { LOG . info ( "StringContentFilter called" ) ; if ( wordsToFilter != null ) { for ( String filterWord : wordsToFilter ) { if ( event . getContent ( ) != null && - 1 != event . getContent ( ) . indexOf ( filterWord ) ) { return true ; } } } return false ; }
Filter event if word occurs in wordsToFilter .
23,576
public String checkIn ( byte [ ] data ) { String id = UUID . randomUUID ( ) . toString ( ) ; dataMap . put ( id , data ) ; return id ; }
Store the given data and return a uuid for later retrieval of the data
23,577
private static void setupFlowId ( SoapMessage message ) { String flowId = FlowIdHelper . getFlowId ( message ) ; if ( flowId == null ) { flowId = FlowIdProtocolHeaderCodec . readFlowId ( message ) ; } if ( flowId == null ) { flowId = FlowIdSoapCodec . readFlowId ( message ) ; } if ( flowId == null ) { Exchange ex = message . getExchange ( ) ; if ( null != ex ) { Message reqMsg = ex . getOutMessage ( ) ; if ( null != reqMsg ) { flowId = FlowIdHelper . getFlowId ( reqMsg ) ; } } } if ( flowId != null && ! flowId . isEmpty ( ) ) { FlowIdHelper . setFlowId ( message , flowId ) ; } }
This functions reads SAM flowId and sets it as message property for subsequent store in CallContext
23,578
private static X509Certificate getReqSigCert ( Message message ) { List < WSHandlerResult > results = CastUtils . cast ( ( List < ? > ) message . getExchange ( ) . getInMessage ( ) . get ( WSHandlerConstants . RECV_RESULTS ) ) ; if ( results == null ) { return null ; } for ( WSHandlerResult rResult : results ) { List < WSSecurityEngineResult > wsSecEngineResults = rResult . getResults ( ) ; for ( WSSecurityEngineResult wser : wsSecEngineResults ) { Integer actInt = ( Integer ) wser . get ( WSSecurityEngineResult . TAG_ACTION ) ; if ( actInt . intValue ( ) == WSConstants . SIGN ) { return ( X509Certificate ) wser . get ( WSSecurityEngineResult . TAG_X509_CERTIFICATE ) ; } } } return null ; }
Refactor the method into public CXF utility and reuse it from CXF instead copy&paste
23,579
private void useSearchService ( ) throws Exception { System . out . println ( "Searching..." ) ; WebClient wc = WebClient . create ( "http://localhost:" + port + "/services/personservice/search" ) ; WebClient . getConfig ( wc ) . getHttpConduit ( ) . getClient ( ) . setReceiveTimeout ( 10000000L ) ; wc . accept ( MediaType . APPLICATION_XML ) ; wc . path ( "person" ) ; SearchConditionBuilder builder = SearchConditionBuilder . instance ( ) ; System . out . println ( "Find people with the name Fred or Lorraine:" ) ; String query = builder . is ( "name" ) . equalTo ( "Fred" ) . or ( ) . is ( "name" ) . equalTo ( "Lorraine" ) . query ( ) ; findPersons ( wc , query ) ; System . out . println ( "Find all people who are no more than 30 years old" ) ; query = builder . is ( "age" ) . lessOrEqualTo ( 30 ) . query ( ) ; findPersons ( wc , query ) ; System . out . println ( "Find all people who are older than 28 and whose father name is John" ) ; query = builder . is ( "age" ) . greaterThan ( 28 ) . and ( "fatherName" ) . equalTo ( "John" ) . query ( ) ; findPersons ( wc , query ) ; System . out . println ( "Find all people who have children with name Fred" ) ; query = builder . is ( "childName" ) . equalTo ( "Fred" ) . query ( ) ; findPersons ( wc , query ) ; wc . reset ( ) . accept ( MediaType . APPLICATION_XML ) ; wc . path ( "personinfo" ) ; System . out . println ( "Find all people younger than 40 using JPA2 Tuples" ) ; query = builder . is ( "age" ) . lessThan ( 40 ) . query ( ) ; wc . path ( query ) ; Collection < ? extends PersonInfo > personInfos = wc . getCollection ( PersonInfo . class ) ; for ( PersonInfo pi : personInfos ) { System . out . println ( "ID : " + pi . getId ( ) ) ; } wc . close ( ) ; }
SearchService is a service which shares the information about Persons with the PersonService . It lets users search for individual people using simple or complex search expressions . The interaction with this service also verifies that the JAX - RS server is capable of supporting multiple root resource classes
23,580
public void useSimpleProxy ( ) { String webAppAddress = "http://localhost:" + port + "/services/personservice" ; PersonService proxy = JAXRSClientFactory . create ( webAppAddress , PersonService . class ) ; new PersonServiceProxyClient ( proxy ) . useService ( ) ; }
This function uses a proxy which is capable of transforming typed invocations into proper HTTP calls which will be understood by RESTful services . This works for subresources as well . Interfaces and concrete classes can be proxified in the latter case a CGLIB runtime dependency is needed . CXF JAX - RS proxies can be configured the same way as HTTP - centric WebClients and response status and headers can also be checked . HTTP response errors can be converted into typed exceptions .
23,581
public static String readCorrelationId ( Message message ) { if ( ! ( message instanceof SoapMessage ) ) { return null ; } String correlationId = null ; Header hdCorrelationId = ( ( SoapMessage ) message ) . getHeader ( CORRELATION_ID_QNAME ) ; if ( hdCorrelationId != null ) { if ( hdCorrelationId . getObject ( ) instanceof String ) { correlationId = ( String ) hdCorrelationId . getObject ( ) ; } else if ( hdCorrelationId . getObject ( ) instanceof Node ) { Node headerNode = ( Node ) hdCorrelationId . getObject ( ) ; correlationId = headerNode . getTextContent ( ) ; } else { LOG . warning ( "Found CorrelationId soap header but value is not a String or a Node! Value: " + hdCorrelationId . getObject ( ) . toString ( ) ) ; } } return correlationId ; }
Read correlation id .
23,582
public static void writeCorrelationId ( Message message , String correlationId ) { if ( ! ( message instanceof SoapMessage ) ) { return ; } SoapMessage soapMessage = ( SoapMessage ) message ; Header hdCorrelationId = soapMessage . getHeader ( CORRELATION_ID_QNAME ) ; if ( hdCorrelationId != null ) { LOG . warning ( "CorrelationId already existing in soap header, need not to write CorrelationId header." ) ; return ; } if ( ( soapMessage . getContent ( javax . xml . stream . XMLStreamWriter . class ) != null ) && ( soapMessage . getContent ( javax . xml . stream . XMLStreamWriter . class ) instanceof SAAJStreamWriter ) && ( ( ( SAAJStreamWriter ) soapMessage . getContent ( javax . xml . stream . XMLStreamWriter . class ) ) . getDocument ( ) . getElementsByTagNameNS ( "http://www.talend.com/esb/sam/correlationId/v1" , "correlationId" ) . getLength ( ) > 0 ) ) { LOG . warning ( "CorrelationId already existing in soap header, need not to write CorrelationId header." ) ; return ; } try { soapMessage . getHeaders ( ) . add ( new Header ( CORRELATION_ID_QNAME , correlationId , new JAXBDataBinding ( String . class ) ) ) ; if ( LOG . isLoggable ( Level . FINE ) ) { LOG . fine ( "Stored correlationId '" + correlationId + "' in soap header: " + CORRELATION_ID_QNAME ) ; } } catch ( JAXBException e ) { LOG . log ( Level . SEVERE , "Couldn't create correlationId header." , e ) ; } }
Write correlation id to message .
23,583
public void handleEvent ( Event event ) { LOG . fine ( "ContentLengthHandler called" ) ; if ( CUT_START_TAG . length ( ) + CUT_END_TAG . length ( ) > length ) { LOG . warning ( "Trying to cut content. But length is shorter then needed for " + CUT_START_TAG + CUT_END_TAG + ". So content is skipped." ) ; event . setContent ( "" ) ; return ; } int currentLength = length - CUT_START_TAG . length ( ) - CUT_END_TAG . length ( ) ; if ( event . getContent ( ) != null && event . getContent ( ) . length ( ) > length ) { LOG . fine ( "cutting content to " + currentLength + " characters. Original length was " + event . getContent ( ) . length ( ) ) ; LOG . fine ( "Content before cutting: " + event . getContent ( ) ) ; event . setContent ( CUT_START_TAG + event . getContent ( ) . substring ( 0 , currentLength ) + CUT_END_TAG ) ; LOG . fine ( "Content after cutting: " + event . getContent ( ) ) ; } }
Cut the message content to the configured length .
23,584
public static XMLGregorianCalendar convertDate ( Date date ) { if ( date == null ) { return null ; } GregorianCalendar gc = new GregorianCalendar ( ) ; gc . setTimeInMillis ( date . getTime ( ) ) ; try { return getDatatypeFactory ( ) . newXMLGregorianCalendar ( gc ) ; } catch ( DatatypeConfigurationException ex ) { return null ; } }
convert Date to XMLGregorianCalendar .
23,585
public static CustomInfo getOrCreateCustomInfo ( Message message ) { CustomInfo customInfo = message . get ( CustomInfo . class ) ; if ( customInfo == null ) { customInfo = new CustomInfo ( ) ; message . put ( CustomInfo . class , customInfo ) ; } return customInfo ; }
Access the customInfo of a message using this accessor . The CustomInfo map will be automatically created and stored in the event if it is not yet present
23,586
public static boolean isMessageContentToBeLogged ( final Message message , final boolean logMessageContent , boolean logMessageContentOverride ) { if ( ! logMessageContentOverride ) { return logMessageContent ; } Object logMessageContentExtObj = message . getContextualProperty ( EXTERNAL_PROPERTY_NAME ) ; if ( null == logMessageContentExtObj ) { return logMessageContent ; } else if ( logMessageContentExtObj instanceof Boolean ) { return ( ( Boolean ) logMessageContentExtObj ) . booleanValue ( ) ; } else if ( logMessageContentExtObj instanceof String ) { String logMessageContentExtVal = ( String ) logMessageContentExtObj ; if ( logMessageContentExtVal . equalsIgnoreCase ( "true" ) ) { return true ; } else if ( logMessageContentExtVal . equalsIgnoreCase ( "false" ) ) { return false ; } else { return logMessageContent ; } } else { return logMessageContent ; } }
If the org . talend . esb . sam . agent . log . messageContent property value is true then log the message content If it is false then skip the message content logging Else fall back to global property log . messageContent
23,587
public void initLocator ( ) throws InterruptedException , ServiceLocatorException { if ( locatorClient == null ) { if ( LOG . isLoggable ( Level . FINE ) ) { LOG . fine ( "Instantiate locatorClient client for Locator Server " + locatorEndpoints + "..." ) ; } ServiceLocatorImpl client = new ServiceLocatorImpl ( ) ; client . setLocatorEndpoints ( locatorEndpoints ) ; client . setConnectionTimeout ( connectionTimeout ) ; client . setSessionTimeout ( sessionTimeout ) ; if ( null != authenticationName ) client . setName ( authenticationName ) ; if ( null != authenticationPassword ) client . setPassword ( authenticationPassword ) ; locatorClient = client ; locatorClient . connect ( ) ; } }
Instantiate Service Locator client . After successful instantiation establish a connection to the Service Locator server . This method will be called if property locatorClient is null . For this purpose was defined additional properties to instantiate ServiceLocatorImpl .
23,588
public void disconnectLocator ( ) throws InterruptedException , ServiceLocatorException { if ( LOG . isLoggable ( Level . FINE ) ) { LOG . fine ( "Destroy Locator client" ) ; } if ( endpointCollector != null ) { endpointCollector . stopScheduledCollection ( ) ; } if ( locatorClient != null ) { locatorClient . disconnect ( ) ; locatorClient = null ; } }
Should use as destroy method . Disconnects from a Service Locator server . All endpoints that were registered before are removed from the server . Set property locatorClient to null .
23,589
List < W3CEndpointReference > lookupEndpoints ( QName serviceName , MatcherDataType matcherData ) throws ServiceLocatorFault , InterruptedExceptionFault { SLPropertiesMatcher matcher = createMatcher ( matcherData ) ; List < String > names = null ; List < W3CEndpointReference > result = new ArrayList < W3CEndpointReference > ( ) ; String adress ; try { initLocator ( ) ; if ( matcher == null ) { names = locatorClient . lookup ( serviceName ) ; } else { names = locatorClient . lookup ( serviceName , matcher ) ; } } catch ( ServiceLocatorException e ) { ServiceLocatorFaultDetail serviceFaultDetail = new ServiceLocatorFaultDetail ( ) ; serviceFaultDetail . setLocatorFaultDetail ( serviceName . toString ( ) + "throws ServiceLocatorFault" ) ; throw new ServiceLocatorFault ( e . getMessage ( ) , serviceFaultDetail ) ; } catch ( InterruptedException e ) { InterruptionFaultDetail interruptionFaultDetail = new InterruptionFaultDetail ( ) ; interruptionFaultDetail . setInterruptionDetail ( serviceName . toString ( ) + "throws InterruptionFault" ) ; throw new InterruptedExceptionFault ( e . getMessage ( ) , interruptionFaultDetail ) ; } if ( names != null && ! names . isEmpty ( ) ) { for ( int i = 0 ; i < names . size ( ) ; i ++ ) { adress = names . get ( i ) ; result . add ( buildEndpoint ( serviceName , adress ) ) ; } } else { if ( LOG . isLoggable ( Level . WARNING ) ) { LOG . log ( Level . WARNING , "lookup Endpoints for " + serviceName + " failed, service is not known." ) ; } ServiceLocatorFaultDetail serviceFaultDetail = new ServiceLocatorFaultDetail ( ) ; serviceFaultDetail . setLocatorFaultDetail ( "lookup Endpoint for " + serviceName + " failed, service is not known." ) ; throw new ServiceLocatorFault ( "Can not find Endpoint" , serviceFaultDetail ) ; } return result ; }
For the given service name return list of endpoint references currently registered at the service locator server endpoints .
23,590
private List < String > getRotatedList ( List < String > strings ) { int index = RANDOM . nextInt ( strings . size ( ) ) ; List < String > rotated = new ArrayList < String > ( ) ; for ( int i = 0 ; i < strings . size ( ) ; i ++ ) { rotated . add ( strings . get ( index ) ) ; index = ( index + 1 ) % strings . size ( ) ; } return rotated ; }
Rotate list of String . Used for randomize selection of received endpoints
23,591
public void start ( String [ ] arguments ) { boolean notStarted = ! started . getAndSet ( true ) ; if ( notStarted ) { start ( new MultiInstanceWorkloadStrategy ( factory , name , arguments , endpointRegistry , execService ) ) ; } }
Start the operation by instantiating the first job instance in a separate Thread .
23,592
protected void processStart ( Endpoint endpoint , EventTypeEnum eventType ) { if ( ! sendLifecycleEvent ) { return ; } Event event = createEvent ( endpoint , eventType ) ; queue . add ( event ) ; }
Process start .
23,593
protected void processStop ( Endpoint endpoint , EventTypeEnum eventType ) { if ( ! sendLifecycleEvent ) { return ; } Event event = createEvent ( endpoint , eventType ) ; monitoringServiceClient . putEvents ( Collections . singletonList ( event ) ) ; if ( LOG . isLoggable ( Level . INFO ) ) { LOG . info ( "Send " + eventType + " event to SAM Server successful!" ) ; } }
Process stop .
23,594
private Event createEvent ( Endpoint endpoint , EventTypeEnum type ) { Event event = new Event ( ) ; MessageInfo messageInfo = new MessageInfo ( ) ; Originator originator = new Originator ( ) ; event . setMessageInfo ( messageInfo ) ; event . setOriginator ( originator ) ; Date date = new Date ( ) ; event . setTimestamp ( date ) ; event . setEventType ( type ) ; messageInfo . setPortType ( endpoint . getBinding ( ) . getBindingInfo ( ) . getService ( ) . getInterface ( ) . getName ( ) . toString ( ) ) ; String transportType = null ; if ( endpoint . getBinding ( ) instanceof SoapBinding ) { SoapBinding soapBinding = ( SoapBinding ) endpoint . getBinding ( ) ; if ( soapBinding . getBindingInfo ( ) instanceof SoapBindingInfo ) { SoapBindingInfo soapBindingInfo = ( SoapBindingInfo ) soapBinding . getBindingInfo ( ) ; transportType = soapBindingInfo . getTransportURI ( ) ; } } messageInfo . setTransportType ( ( transportType != null ) ? transportType : "Unknown transport type" ) ; originator . setProcessId ( Converter . getPID ( ) ) ; try { InetAddress inetAddress = InetAddress . getLocalHost ( ) ; originator . setIp ( inetAddress . getHostAddress ( ) ) ; originator . setHostname ( inetAddress . getHostName ( ) ) ; } catch ( UnknownHostException e ) { originator . setHostname ( "Unknown hostname" ) ; originator . setIp ( "Unknown ip address" ) ; } String address = endpoint . getEndpointInfo ( ) . getAddress ( ) ; event . getCustomInfo ( ) . put ( "address" , address ) ; return event ; }
Creates the event for endpoint with specific type .
23,595
public void useOldRESTService ( ) throws Exception { List < Object > providers = createJAXRSProviders ( ) ; com . example . customerservice . CustomerService customerService = JAXRSClientFactory . createFromModel ( "http://localhost:" + port + "/examples/direct/rest" , com . example . customerservice . CustomerService . class , "classpath:/model/CustomerService-jaxrs.xml" , providers , null ) ; System . out . println ( "Using old RESTful CustomerService with old client" ) ; customer . v1 . Customer customer = createOldCustomer ( "Smith Old REST" ) ; customerService . updateCustomer ( customer ) ; customer = customerService . getCustomerByName ( "Smith Old REST" ) ; printOldCustomerDetails ( customer ) ; }
Old REST client uses old REST service
23,596
public void useNewRESTService ( String address ) throws Exception { List < Object > providers = createJAXRSProviders ( ) ; org . customer . service . CustomerService customerService = JAXRSClientFactory . createFromModel ( address , org . customer . service . CustomerService . class , "classpath:/model/CustomerService-jaxrs.xml" , providers , null ) ; System . out . println ( "Using new RESTful CustomerService with new client" ) ; customer . v2 . Customer customer = createNewCustomer ( "Smith New REST" ) ; customerService . updateCustomer ( customer ) ; customer = customerService . getCustomerByName ( "Smith New REST" ) ; printNewCustomerDetails ( customer ) ; }
New REST client uses new REST service
23,597
public void useNewRESTServiceWithOldClient ( ) throws Exception { List < Object > providers = createJAXRSProviders ( ) ; com . example . customerservice . CustomerService customerService = JAXRSClientFactory . createFromModel ( "http://localhost:" + port + "/examples/direct/new-rest" , com . example . customerservice . CustomerService . class , "classpath:/model/CustomerService-jaxrs.xml" , providers , null ) ; ClientConfiguration config = WebClient . getConfig ( customerService ) ; addTransformInterceptors ( config . getInInterceptors ( ) , config . getOutInterceptors ( ) , false ) ; System . out . println ( "Using new RESTful CustomerService with old Client" ) ; customer . v1 . Customer customer = createOldCustomer ( "Smith Old to New REST" ) ; customerService . updateCustomer ( customer ) ; customer = customerService . getCustomerByName ( "Smith Old to New REST" ) ; printOldCustomerDetails ( customer ) ; }
Old REST client uses new REST service
23,598
public void init ( ) { if ( bus != null && sendLifecycleEvent ) { ServerLifeCycleManager slcm = bus . getExtension ( ServerLifeCycleManager . class ) ; if ( null != slcm ) { ServiceListenerImpl svrListener = new ServiceListenerImpl ( ) ; svrListener . setSendLifecycleEvent ( sendLifecycleEvent ) ; svrListener . setQueue ( queue ) ; svrListener . setMonitoringServiceClient ( monitoringServiceClient ) ; slcm . registerListener ( svrListener ) ; } ClientLifeCycleManager clcm = bus . getExtension ( ClientLifeCycleManager . class ) ; if ( null != clcm ) { ClientListenerImpl cltListener = new ClientListenerImpl ( ) ; cltListener . setSendLifecycleEvent ( sendLifecycleEvent ) ; cltListener . setQueue ( queue ) ; cltListener . setMonitoringServiceClient ( monitoringServiceClient ) ; clcm . registerListener ( cltListener ) ; } } if ( executorQueueSize == 0 ) { executor = Executors . newFixedThreadPool ( this . executorPoolSize ) ; } else { executor = new ThreadPoolExecutor ( executorPoolSize , executorPoolSize , 0 , TimeUnit . SECONDS , new LinkedBlockingQueue < Runnable > ( executorQueueSize ) , Executors . defaultThreadFactory ( ) , new RejectedExecutionHandlerImpl ( ) ) ; } scheduler = new Timer ( ) ; scheduler . scheduleAtFixedRate ( new TimerTask ( ) { public void run ( ) { sendEventsFromQueue ( ) ; } } , 0 , getDefaultInterval ( ) ) ; }
Instantiates a new event collector .
23,599
public void setDefaultInterval ( long defaultInterval ) { if ( defaultInterval <= 0 ) { LOG . severe ( "collector.scheduler.interval must be greater than 0. Recommended value is 500-1000. Current value is " + defaultInterval ) ; throw new IllegalArgumentException ( "collector.scheduler.interval must be greater than 0. Recommended value is 500-1000. Current value is " + defaultInterval ) ; } this . defaultInterval = defaultInterval ; }
Set default interval for sending events to monitoring service . DefaultInterval will be used by scheduler .