_id
stringlengths 2
7
| title
stringlengths 3
140
| partition
stringclasses 3
values | text
stringlengths 73
34.1k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q3800
|
MonitoringServiceWrapper.putEvents
|
train
|
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);
}
}
|
java
|
{
"resource": ""
}
|
q3801
|
AgentActivator.createEventType
|
train
|
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;
}
|
java
|
{
"resource": ""
}
|
q3802
|
AgentActivator.putEvent
|
train
|
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");
}
}
|
java
|
{
"resource": ""
}
|
q3803
|
AgentActivator.checkConfig
|
train
|
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"));
}
|
java
|
{
"resource": ""
}
|
q3804
|
AgentActivator.initWsClient
|
train
|
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();
}
|
java
|
{
"resource": ""
}
|
q3805
|
FlowIdProducerOut.handleResponseOut
|
train
|
protected void handleResponseOut(T message) throws Fault {
Message reqMsg = message.getExchange().getInMessage();
if (reqMsg == null) {
LOG.warning("InMessage is null!");
return;
}
// No flowId for oneway message
Exchange ex = reqMsg.getExchange();
if (ex.isOneWay()) {
return;
}
String reqFid = FlowIdHelper.getFlowId(reqMsg);
// if some interceptor throws fault before FlowIdProducerIn fired
if (reqFid == null) {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("Some interceptor throws fault.Setting FlowId in response.");
}
reqFid = FlowIdProtocolHeaderCodec.readFlowId(message);
}
// write IN message to SAM repo in case fault
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();
// write IN message to SAM repo in case fault
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);
}
|
java
|
{
"resource": ""
}
|
q3806
|
FlowIdProducerOut.handleRequestOut
|
train
|
protected void handleRequestOut(T message) throws Fault {
String flowId = FlowIdHelper.getFlowId(message);
if (flowId == null
&& message.containsKey(PhaseInterceptorChain.PREVIOUS_MESSAGE)) {
// Web Service consumer is acting as an intermediary
@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) {
// No flowId found. Generate one.
flowId = ContextUtils.generateUUID();
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("Generate new flowId '" + flowId + "'");
}
}
FlowIdHelper.setFlowId(message, flowId);
}
|
java
|
{
"resource": ""
}
|
q3807
|
FlowIdProducerOut.handleINEvent
|
train
|
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);
}
}
}
|
java
|
{
"resource": ""
}
|
q3808
|
DBInitializer.setDialect
|
train
|
public void setDialect(String dialect) {
String[] scripts = createScripts.get(dialect);
createSql = scripts[0];
createSqlInd = scripts[1];
}
|
java
|
{
"resource": ""
}
|
q3809
|
EventTypeMapper.map
|
train
|
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;
}
|
java
|
{
"resource": ""
}
|
q3810
|
EventTypeMapper.mapCustomInfo
|
train
|
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;
}
|
java
|
{
"resource": ""
}
|
q3811
|
EventTypeMapper.mapContent
|
train
|
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);
}
}
|
java
|
{
"resource": ""
}
|
q3812
|
EventTypeMapper.mapMessageInfo
|
train
|
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;
}
|
java
|
{
"resource": ""
}
|
q3813
|
EventTypeMapper.mapOriginatorType
|
train
|
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;
}
|
java
|
{
"resource": ""
}
|
q3814
|
EventTypeMapper.mapEventTypeEnum
|
train
|
private static EventTypeEnum mapEventTypeEnum(EventEnumType eventType) {
if (eventType != null) {
return EventTypeEnum.valueOf(eventType.name());
}
return EventTypeEnum.UNKNOWN;
}
|
java
|
{
"resource": ""
}
|
q3815
|
SOAPClient.useNewSOAPService
|
train
|
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);
}
|
java
|
{
"resource": ""
}
|
q3816
|
SOAPClient.useNewSOAPServiceWithOldClient
|
train
|
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();
// The outgoing new Customer data needs to be transformed for
// the old service to understand it and the response from the old service
// needs to be transformed for this new client to understand it.
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);
}
|
java
|
{
"resource": ""
}
|
q3817
|
SOAPClient.useNewSOAPServiceWithOldClientAndRedirection
|
train
|
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);
}
|
java
|
{
"resource": ""
}
|
q3818
|
SOAPClient.addTransformInterceptors
|
train
|
private void addTransformInterceptors(List<Interceptor<?>> inInterceptors,
List<Interceptor<?>> outInterceptors,
boolean newClient) {
// The old service expects the Customer data be qualified with
// the 'http://customer/v1' namespace.
// The new service expects the Customer data be qualified with
// the 'http://customer/v2' namespace.
// If it is an old client talking to the new service then:
// - the out transformation interceptor is configured for
// 'http://customer/v1' qualified data be transformed into
// 'http://customer/v2' qualified data.
// - the in transformation interceptor is configured for
// 'http://customer/v2' qualified response data be transformed into
// 'http://customer/v1' qualified data.
// If it is a new client talking to the old service then:
// - the out transformation interceptor is configured for
// 'http://customer/v2' qualified data be transformed into
// 'http://customer/v1' qualified data.
// - the in transformation interceptor is configured for
// 'http://customer/v1' qualified response data be transformed into
// 'http://customer/v2' qualified data.
// - new Customer type also introduces a briefDescription property
// which needs to be dropped for the old service validation to succeed
// this configuration can be provided externally
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", "");
//outTransform.setOutDropElements(
// Collections.singletonList("{http://customer/v2}briefDescription"));
}
TransformInInterceptor inTransform = new TransformInInterceptor();
inTransform.setInTransformElements(newClient ? oldToNewTransformMap
: newToOldTransformMap);
inInterceptors.add(inTransform);
outInterceptors.add(outTransform);
}
|
java
|
{
"resource": ""
}
|
q3819
|
Person.getXmlID
|
train
|
@SuppressWarnings("unused")
@XmlID
@XmlAttribute(name = "id")
private String getXmlID(){
return String.format("%s-%s", this.getClass().getSimpleName(), Long.valueOf(id));
}
|
java
|
{
"resource": ""
}
|
q3820
|
LocatorLifecycleStrategy.stopAllServersAndRemoveCamelContext
|
train
|
private void stopAllServersAndRemoveCamelContext(CamelContext camelContext) {
log.debug("Stopping all servers associated with {}", camelContext);
List<SingleBusLocatorRegistrar> registrars = locatorRegistrar.getAllRegistars(camelContext);
registrars.forEach(registrar -> registrar.stopAllServersAndRemoveCamelContext());
}
|
java
|
{
"resource": ""
}
|
q3821
|
EventMapper.map
|
train
|
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;
}
|
java
|
{
"resource": ""
}
|
q3822
|
EventMapper.getDataHandlerForString
|
train
|
private static DataHandler getDataHandlerForString(Event event) {
try {
return new DataHandler(new ByteDataSource(event.getContent().getBytes("UTF-8")));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
|
java
|
{
"resource": ""
}
|
q3823
|
EventMapper.mapMessageInfo
|
train
|
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;
}
|
java
|
{
"resource": ""
}
|
q3824
|
EventMapper.mapOriginator
|
train
|
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;
}
|
java
|
{
"resource": ""
}
|
q3825
|
EventMapper.convertCustomInfo
|
train
|
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;
}
|
java
|
{
"resource": ""
}
|
q3826
|
EventMapper.convertEventType
|
train
|
private static EventEnumType convertEventType(org.talend.esb.sam.common.event.EventTypeEnum eventType) {
if (eventType == null) {
return null;
}
return EventEnumType.valueOf(eventType.name());
}
|
java
|
{
"resource": ""
}
|
q3827
|
EventMapper.convertString
|
train
|
private static QName convertString(String str) {
if (str != null) {
return QName.valueOf(str);
} else {
return null;
}
}
|
java
|
{
"resource": ""
}
|
q3828
|
MonitoringException.logException
|
train
|
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);
}
|
java
|
{
"resource": ""
}
|
q3829
|
LocatorClientEnabler.getLocatorSelectionStrategy
|
train
|
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();
}
}
|
java
|
{
"resource": ""
}
|
q3830
|
LocatorClientEnabler.setDefaultLocatorSelectionStrategy
|
train
|
@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.");
}
}
|
java
|
{
"resource": ""
}
|
q3831
|
LocatorClientEnabler.enable
|
train
|
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");
}
}
|
java
|
{
"resource": ""
}
|
q3832
|
RequestCallbackFeature.applyWsdlExtensions
|
train
|
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);
}
}
|
java
|
{
"resource": ""
}
|
q3833
|
EventFeatureImpl.setQueue
|
train
|
@Inject
public void setQueue(EventQueue queue) {
if (epi == null) {
MessageToEventMapper mapper = new MessageToEventMapper();
mapper.setMaxContentLength(maxContentLength);
epi = new EventProducerInterceptor(mapper, queue);
}
}
|
java
|
{
"resource": ""
}
|
q3834
|
EventFeatureImpl.detectWSAddressingFeature
|
train
|
private boolean detectWSAddressingFeature(InterceptorProvider provider, Bus bus) {
//detect on the bus level
if (bus.getFeatures() != null) {
Iterator<Feature> busFeatures = bus.getFeatures().iterator();
while (busFeatures.hasNext()) {
Feature busFeature = busFeatures.next();
if (busFeature instanceof WSAddressingFeature) {
return true;
}
}
}
//detect on the endpoint/client level
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;
}
|
java
|
{
"resource": ""
}
|
q3835
|
EventFeatureImpl.addWSAddressingInterceptors
|
train
|
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);
}
|
java
|
{
"resource": ""
}
|
q3836
|
FlowIdSoapCodec.readFlowId
|
train
|
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;
}
|
java
|
{
"resource": ""
}
|
q3837
|
FlowIdSoapCodec.writeFlowId
|
train
|
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);
}
}
|
java
|
{
"resource": ""
}
|
q3838
|
STSClientUtils.createSTSX509Client
|
train
|
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;
}
|
java
|
{
"resource": ""
}
|
q3839
|
SingleBusLocatorRegistrar.isSecuredByPolicy
|
train
|
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;
}
|
java
|
{
"resource": ""
}
|
q3840
|
SingleBusLocatorRegistrar.isSecuredByProperty
|
train
|
private boolean isSecuredByProperty(Server server) {
boolean isSecured = false;
Object value = server.getEndpoint().get("org.talend.tesb.endpoint.secured"); //Property name TBD
if (value instanceof String) {
try {
isSecured = Boolean.valueOf((String) value);
} catch (Exception ex) {
}
}
return isSecured;
}
|
java
|
{
"resource": ""
}
|
q3841
|
EventRepositoryImpl.writeCustomInfo
|
train
|
private void writeCustomInfo(Event event) {
// insert customInfo (key/value) into DB
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());
}
}
|
java
|
{
"resource": ""
}
|
q3842
|
EventRepositoryImpl.readCustomInfo
|
train
|
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;
}
|
java
|
{
"resource": ""
}
|
q3843
|
PatternCriteria.toSQLPattern
|
train
|
private String toSQLPattern(String attribute) {
String pattern = attribute.replace("*", "%");
if (!pattern.startsWith("%")) {
pattern = "%" + pattern;
}
if (!pattern.endsWith("%")) {
pattern = pattern.concat("%");
}
return pattern;
}
|
java
|
{
"resource": ""
}
|
q3844
|
EventProducerInterceptor.checkMessageID
|
train
|
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);
}
}
|
java
|
{
"resource": ""
}
|
q3845
|
CorrelationIdHelper.getCorrelationId
|
train
|
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;
}
|
java
|
{
"resource": ""
}
|
q3846
|
CorrelationIdHelper.readCorrelationId
|
train
|
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;
}
|
java
|
{
"resource": ""
}
|
q3847
|
CorrelationIdHelper.getOrCreateProtocolHeader
|
train
|
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;
}
|
java
|
{
"resource": ""
}
|
q3848
|
MonitoringServiceImpl.putEvents
|
train
|
public void putEvents(List<Event> events) {
List<Event> filteredEvents = filterEvents(events);
executeHandlers(filteredEvents);
for (Event event : filteredEvents) {
persistenceHandler.writeEvent(event);
}
}
|
java
|
{
"resource": ""
}
|
q3849
|
MonitoringServiceImpl.filterEvents
|
train
|
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;
}
|
java
|
{
"resource": ""
}
|
q3850
|
StringContentFilter.filter
|
train
|
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;
}
|
java
|
{
"resource": ""
}
|
q3851
|
DataStore.checkIn
|
train
|
public String checkIn(byte[] data) {
String id = UUID.randomUUID().toString();
dataMap.put(id, data);
return id;
}
|
java
|
{
"resource": ""
}
|
q3852
|
RequestCallbackInInterceptor.setupFlowId
|
train
|
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);
}
}
|
java
|
{
"resource": ""
}
|
q3853
|
RequestCallbackInInterceptor.getReqSigCert
|
train
|
private static X509Certificate getReqSigCert(Message message) {
List<WSHandlerResult> results =
CastUtils.cast((List<?>)
message.getExchange().getInMessage().get(WSHandlerConstants.RECV_RESULTS));
if (results == null) {
return null;
}
/*
* Scan the results for a matching actor. Use results only if the
* receiving Actor and the sending Actor match.
*/
for (WSHandlerResult rResult : results) {
List<WSSecurityEngineResult> wsSecEngineResults = rResult
.getResults();
/*
* Scan the results for the first Signature action. Use the
* certificate of this Signature to set the certificate for the
* encryption action :-).
*/
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;
}
|
java
|
{
"resource": ""
}
|
q3854
|
RESTClient.useSearchService
|
train
|
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);
// Moves to "/services/personservice/search"
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);
//Moves to "/services/personservice/personinfo"
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();
// Use URI path component to capture the query expression
wc.path(query);
Collection<? extends PersonInfo> personInfos = wc.getCollection(PersonInfo.class);
for (PersonInfo pi : personInfos) {
System.out.println("ID : " + pi.getId());
}
wc.close();
}
|
java
|
{
"resource": ""
}
|
q3855
|
RESTClient.useSimpleProxy
|
train
|
public void useSimpleProxy() {
String webAppAddress = "http://localhost:" + port + "/services/personservice";
PersonService proxy = JAXRSClientFactory.create(webAppAddress, PersonService.class);
new PersonServiceProxyClient(proxy).useService();
}
|
java
|
{
"resource": ""
}
|
q3856
|
CorrelationIdSoapCodec.readCorrelationId
|
train
|
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;
}
|
java
|
{
"resource": ""
}
|
q3857
|
CorrelationIdSoapCodec.writeCorrelationId
|
train
|
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);
}
}
|
java
|
{
"resource": ""
}
|
q3858
|
ContentLengthHandler.handleEvent
|
train
|
public void handleEvent(Event event) {
LOG.fine("ContentLengthHandler called");
//if maximum length is shorter then <cut><![CDATA[ ]]></cut> it's not possible to cut the content
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());
}
}
|
java
|
{
"resource": ""
}
|
q3859
|
Converter.convertDate
|
train
|
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;
}
}
|
java
|
{
"resource": ""
}
|
q3860
|
CustomInfo.getOrCreateCustomInfo
|
train
|
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;
}
|
java
|
{
"resource": ""
}
|
q3861
|
WireTapHelper.isMessageContentToBeLogged
|
train
|
public static boolean isMessageContentToBeLogged(final Message message, final boolean logMessageContent,
boolean logMessageContentOverride) {
/*
* If controlling of logging behavior is not allowed externally
* then log according to global property value
*/
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;
}
}
|
java
|
{
"resource": ""
}
|
q3862
|
LocatorSoapServiceImpl.initLocator
|
train
|
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();
}
}
|
java
|
{
"resource": ""
}
|
q3863
|
LocatorSoapServiceImpl.disconnectLocator
|
train
|
@PreDestroy
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;
}
}
|
java
|
{
"resource": ""
}
|
q3864
|
LocatorSoapServiceImpl.lookupEndpoints
|
train
|
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;
}
|
java
|
{
"resource": ""
}
|
q3865
|
LocatorSoapServiceImpl.getRotatedList
|
train
|
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;
}
|
java
|
{
"resource": ""
}
|
q3866
|
MultiThreadedOperation.start
|
train
|
@Override
public void start(String[] arguments) {
boolean notStarted = !started.getAndSet(true);
if (notStarted) {
start(new MultiInstanceWorkloadStrategy(factory, name, arguments, endpointRegistry, execService));
}
}
|
java
|
{
"resource": ""
}
|
q3867
|
AbstractListenerImpl.processStart
|
train
|
protected void processStart(Endpoint endpoint, EventTypeEnum eventType) {
if (!sendLifecycleEvent) {
return;
}
Event event = createEvent(endpoint, eventType);
queue.add(event);
}
|
java
|
{
"resource": ""
}
|
q3868
|
AbstractListenerImpl.processStop
|
train
|
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!");
}
}
|
java
|
{
"resource": ""
}
|
q3869
|
AbstractListenerImpl.createEvent
|
train
|
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;
}
|
java
|
{
"resource": ""
}
|
q3870
|
RESTClient.useOldRESTService
|
train
|
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);
}
|
java
|
{
"resource": ""
}
|
q3871
|
RESTClient.useNewRESTService
|
train
|
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);
}
|
java
|
{
"resource": ""
}
|
q3872
|
RESTClient.useNewRESTServiceWithOldClient
|
train
|
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);
// The outgoing old Customer data needs to be transformed for
// the new service to understand it and the response from the new service
// needs to be transformed for this old client to understand it.
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);
}
|
java
|
{
"resource": ""
}
|
q3873
|
EventCollector.init
|
train
|
@PostConstruct
public void init() {
//init Bus and LifeCycle listeners
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());
}
|
java
|
{
"resource": ""
}
|
q3874
|
EventCollector.setDefaultInterval
|
train
|
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;
}
|
java
|
{
"resource": ""
}
|
q3875
|
EventCollector.sendEventsFromQueue
|
train
|
public void sendEventsFromQueue() {
if (null == queue || stopSending) {
return;
}
LOG.fine("Scheduler called for sending events");
int packageSize = getEventsPerMessageCall();
while (!queue.isEmpty()) {
final List<Event> list = new ArrayList<Event>();
int i = 0;
while (i < packageSize && !queue.isEmpty()) {
Event event = queue.remove();
if (event != null && !filter(event)) {
list.add(event);
i++;
}
}
if (list.size() > 0) {
executor.execute(new Runnable() {
public void run() {
try {
sendEvents(list);
} catch (MonitoringException e) {
e.logException(Level.SEVERE);
}
}
});
}
}
}
|
java
|
{
"resource": ""
}
|
q3876
|
EventCollector.sendEvents
|
train
|
private void sendEvents(final List<Event> events) {
if (null != handlers) {
for (EventHandler current : handlers) {
for (Event event : events) {
current.handleEvent(event);
}
}
}
LOG.info("Put events(" + events.size() + ") to Monitoring Server.");
try {
if (sendToEventadmin) {
EventAdminPublisher.publish(events);
} else {
monitoringServiceClient.putEvents(events);
}
} catch (MonitoringException e) {
throw e;
} catch (Exception e) {
throw new MonitoringException("002",
"Unknown error while execute put events to Monitoring Server", e);
}
}
|
java
|
{
"resource": ""
}
|
q3877
|
SingleThreadedOperation.start
|
train
|
@Override
public void start(String[] arguments) {
boolean notStarted = !started.getAndSet(true);
if (notStarted) {
start(new SingleInstanceWorkloadStrategy(job, name, arguments, endpointRegistry, execService));
}
}
|
java
|
{
"resource": ""
}
|
q3878
|
CorrelationIdProtocolHeaderCodec.writeCorrelationId
|
train
|
public static void writeCorrelationId(Message message, String correlationId) {
Map<String, List<String>> headers = getOrCreateProtocolHeader(message);
headers.put(CORRELATIONID_HTTP_HEADER_NAME, Collections.singletonList(correlationId));
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("HTTP header '" + CORRELATIONID_HTTP_HEADER_NAME + "' set to: " + correlationId);
}
}
|
java
|
{
"resource": ""
}
|
q3879
|
FlowIdProtocolHeaderCodec.readFlowId
|
train
|
public static String readFlowId(Message message) {
String flowId = null;
Map<String, List<String>> headers = getOrCreateProtocolHeader(message);
List<String> flowIds = headers.get(FLOWID_HTTP_HEADER_NAME);
if (flowIds != null && flowIds.size() > 0) {
flowId = flowIds.get(0);
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("HTTP header '" + FLOWID_HTTP_HEADER_NAME + "' found: " + flowId);
}
} else {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("No HTTP header '" + FLOWID_HTTP_HEADER_NAME + "' found");
}
}
return flowId;
}
|
java
|
{
"resource": ""
}
|
q3880
|
FlowIdProtocolHeaderCodec.writeFlowId
|
train
|
public static void writeFlowId(Message message, String flowId) {
Map<String, List<String>> headers = getOrCreateProtocolHeader(message);
headers.put(FLOWID_HTTP_HEADER_NAME, Collections.singletonList(flowId));
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("HTTP header '" + FLOWID_HTTP_HEADER_NAME + "' set to: " + flowId);
}
}
|
java
|
{
"resource": ""
}
|
q3881
|
DemoInterceptor.addInterceptors
|
train
|
public static void addInterceptors(InterceptorProvider provider) {
PhaseManager phases = BusFactory.getDefaultBus().getExtension(PhaseManager.class);
for (Phase p : phases.getInPhases()) {
provider.getInInterceptors().add(new DemoInterceptor(p.getName()));
provider.getInFaultInterceptors().add(new DemoInterceptor(p.getName()));
}
for (Phase p : phases.getOutPhases()) {
provider.getOutInterceptors().add(new DemoInterceptor(p.getName()));
provider.getOutFaultInterceptors().add(new DemoInterceptor(p.getName()));
}
}
|
java
|
{
"resource": ""
}
|
q3882
|
DemoInterceptor.somethingMayHaveChanged
|
train
|
private boolean somethingMayHaveChanged(PhaseInterceptorChain pic) {
Iterator<Interceptor<? extends Message>> it = pic.iterator();
Interceptor<? extends Message> last = null;
while (it.hasNext()) {
Interceptor<? extends Message> cur = it.next();
if (cur == this) {
if (last instanceof DemoInterceptor) {
return false;
}
return true;
}
last = cur;
}
return true;
}
|
java
|
{
"resource": ""
}
|
q3883
|
DemoInterceptor.printInterceptorChain
|
train
|
public void printInterceptorChain(InterceptorChain chain) {
Iterator<Interceptor<? extends Message>> it = chain.iterator();
String phase = "";
StringBuilder builder = null;
while (it.hasNext()) {
Interceptor<? extends Message> interceptor = it.next();
if (interceptor instanceof DemoInterceptor) {
continue;
}
if (interceptor instanceof PhaseInterceptor) {
PhaseInterceptor pi = (PhaseInterceptor)interceptor;
if (!phase.equals(pi.getPhase())) {
if (builder != null) {
System.out.println(builder.toString());
} else {
builder = new StringBuilder(100);
}
builder.setLength(0);
builder.append(" ");
builder.append(pi.getPhase());
builder.append(": ");
phase = pi.getPhase();
}
String id = pi.getId();
int idx = id.lastIndexOf('.');
if (idx != -1) {
id = id.substring(idx + 1);
}
builder.append(id);
builder.append(' ');
}
}
}
|
java
|
{
"resource": ""
}
|
q3884
|
LocationApi.getCharactersCharacterIdShipCall
|
train
|
public com.squareup.okhttp.Call getCharactersCharacterIdShipCall(Integer characterId, String datasource,
String ifNoneMatch, String token, final ApiCallback callback) throws ApiException {
Object localVarPostBody = new Object();
// create path and map variables
String localVarPath = "/v1/characters/{character_id}/ship/".replaceAll("\\{" + "character_id" + "\\}",
apiClient.escapeString(characterId.toString()));
List<Pair> localVarQueryParams = new ArrayList<Pair>();
List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>();
if (datasource != null) {
localVarQueryParams.addAll(apiClient.parameterToPair("datasource", datasource));
}
if (token != null) {
localVarQueryParams.addAll(apiClient.parameterToPair("token", token));
}
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
if (ifNoneMatch != null) {
localVarHeaderParams.put("If-None-Match", apiClient.parameterToString(ifNoneMatch));
}
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
final String[] localVarAccepts = { "application/json" };
final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
if (localVarAccept != null) {
localVarHeaderParams.put("Accept", localVarAccept);
}
final String[] localVarContentTypes = {
};
final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
localVarHeaderParams.put("Content-Type", localVarContentType);
String[] localVarAuthNames = new String[] { "evesso" };
return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams,
localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, callback);
}
|
java
|
{
"resource": ""
}
|
q3885
|
OAuth.getAuthorizationUri
|
train
|
public String getAuthorizationUri(final String redirectUri, final Set<String> scopes, final String state) {
if (account == null)
throw new IllegalArgumentException("Auth is not set");
if (account.getClientId() == null)
throw new IllegalArgumentException("client_id is not set");
StringBuilder builder = new StringBuilder();
builder.append(URI_AUTHENTICATION);
builder.append("?");
builder.append("response_type=");
builder.append(encode("code"));
builder.append("&redirect_uri=");
builder.append(encode(redirectUri));
builder.append("&client_id=");
builder.append(encode(account.getClientId()));
builder.append("&scope=");
builder.append(encode(getScopesString(scopes)));
builder.append("&state=");
builder.append(encode(state));
builder.append("&code_challenge");
builder.append(getCodeChallenge()); // Already url encoded
builder.append("&code_challenge_method=");
builder.append(encode("S256"));
return builder.toString();
}
|
java
|
{
"resource": ""
}
|
q3886
|
OAuth.finishFlow
|
train
|
public void finishFlow(final String code, final String state) throws ApiException {
if (account == null)
throw new IllegalArgumentException("Auth is not set");
if (codeVerifier == null)
throw new IllegalArgumentException("code_verifier is not set");
if (account.getClientId() == null)
throw new IllegalArgumentException("client_id is not set");
StringBuilder builder = new StringBuilder();
builder.append("grant_type=");
builder.append(encode("authorization_code"));
builder.append("&client_id=");
builder.append(encode(account.getClientId()));
builder.append("&code=");
builder.append(encode(code));
builder.append("&code_verifier=");
builder.append(encode(codeVerifier));
update(account, builder.toString());
}
|
java
|
{
"resource": ""
}
|
q3887
|
MetaApi.getPingWithHttpInfo
|
train
|
public ApiResponse<String> getPingWithHttpInfo() throws ApiException {
com.squareup.okhttp.Call call = getPingValidateBeforeCall(null);
Type localVarReturnType = new TypeToken<String>() {
}.getType();
return apiClient.execute(call, localVarReturnType);
}
|
java
|
{
"resource": ""
}
|
q3888
|
ApiClient.setHttpClient
|
train
|
public ApiClient setHttpClient(OkHttpClient newHttpClient) {
if (!httpClient.equals(newHttpClient)) {
newHttpClient.networkInterceptors().addAll(httpClient.networkInterceptors());
httpClient.networkInterceptors().clear();
newHttpClient.interceptors().addAll(httpClient.interceptors());
httpClient.interceptors().clear();
this.httpClient = newHttpClient;
}
return this;
}
|
java
|
{
"resource": ""
}
|
q3889
|
ApiClient.addProgressInterceptor
|
train
|
private void addProgressInterceptor() {
httpClient.networkInterceptors().add(new Interceptor() {
@Override
public Response intercept(Interceptor.Chain chain) throws IOException {
final Request request = chain.request();
final Response originalResponse = chain.proceed(request);
if (request.tag() instanceof ApiCallback) {
final ApiCallback callback = (ApiCallback) request.tag();
return originalResponse.newBuilder()
.body(new ProgressResponseBody(originalResponse.body(), callback)).build();
}
return originalResponse;
}
});
}
|
java
|
{
"resource": ""
}
|
q3890
|
UserInterfaceApi.postUiAutopilotWaypointCall
|
train
|
public com.squareup.okhttp.Call postUiAutopilotWaypointCall(Boolean addToBeginning, Boolean clearOtherWaypoints,
Long destinationId, String datasource, String token, final ApiCallback callback) throws ApiException {
Object localVarPostBody = new Object();
// create path and map variables
String localVarPath = "/v2/ui/autopilot/waypoint/";
List<Pair> localVarQueryParams = new ArrayList<Pair>();
List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>();
if (addToBeginning != null) {
localVarQueryParams.addAll(apiClient.parameterToPair("add_to_beginning", addToBeginning));
}
if (clearOtherWaypoints != null) {
localVarQueryParams.addAll(apiClient.parameterToPair("clear_other_waypoints", clearOtherWaypoints));
}
if (datasource != null) {
localVarQueryParams.addAll(apiClient.parameterToPair("datasource", datasource));
}
if (destinationId != null) {
localVarQueryParams.addAll(apiClient.parameterToPair("destination_id", destinationId));
}
if (token != null) {
localVarQueryParams.addAll(apiClient.parameterToPair("token", token));
}
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
final String[] localVarAccepts = {
};
final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
if (localVarAccept != null) {
localVarHeaderParams.put("Accept", localVarAccept);
}
final String[] localVarContentTypes = {
};
final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
localVarHeaderParams.put("Content-Type", localVarContentType);
String[] localVarAuthNames = new String[] { "evesso" };
return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams,
localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, callback);
}
|
java
|
{
"resource": ""
}
|
q3891
|
CircleProgressBar.setColorSchemeResources
|
train
|
public void setColorSchemeResources(int... colorResIds) {
final Resources res = getResources();
int[] colorRes = new int[colorResIds.length];
for (int i = 0; i < colorResIds.length; i++) {
colorRes[i] = res.getColor(colorResIds[i]);
}
setColorSchemeColors(colorRes);
}
|
java
|
{
"resource": ""
}
|
q3892
|
CircleProgressBar.setBackgroundColor
|
train
|
public void setBackgroundColor(int colorRes) {
if (getBackground() instanceof ShapeDrawable) {
final Resources res = getResources();
((ShapeDrawable) getBackground()).getPaint().setColor(res.getColor(colorRes));
}
}
|
java
|
{
"resource": ""
}
|
q3893
|
DataBarExpanded.logBinaryStringInfo
|
train
|
private void logBinaryStringInfo(StringBuilder binaryString) {
encodeInfo += "Binary Length: " + binaryString.length() + "\n";
encodeInfo += "Binary String: ";
int nibble = 0;
for (int i = 0; i < binaryString.length(); i++) {
switch (i % 4) {
case 0:
if (binaryString.charAt(i) == '1') {
nibble += 8;
}
break;
case 1:
if (binaryString.charAt(i) == '1') {
nibble += 4;
}
break;
case 2:
if (binaryString.charAt(i) == '1') {
nibble += 2;
}
break;
case 3:
if (binaryString.charAt(i) == '1') {
nibble += 1;
}
encodeInfo += Integer.toHexString(nibble);
nibble = 0;
break;
}
}
if ((binaryString.length() % 4) != 0) {
encodeInfo += Integer.toHexString(nibble);
}
encodeInfo += "\n";
}
|
java
|
{
"resource": ""
}
|
q3894
|
Code128.combineSubsetBlocks
|
train
|
private int combineSubsetBlocks(Mode[] mode_type, int[] mode_length, int index_point) {
/* bring together same type blocks */
if (index_point > 1) {
for (int i = 1; i < index_point; i++) {
if (mode_type[i - 1] == mode_type[i]) {
/* bring together */
mode_length[i - 1] = mode_length[i - 1] + mode_length[i];
/* decrease the list */
for (int j = i + 1; j < index_point; j++) {
mode_length[j - 1] = mode_length[j];
mode_type[j - 1] = mode_type[j];
}
index_point--;
i--;
}
}
}
return index_point;
}
|
java
|
{
"resource": ""
}
|
q3895
|
OkapiBarcode.main
|
train
|
public static void main(String[] args) {
Settings settings = new Settings();
new JCommander(settings, args);
if (!settings.isGuiSupressed()) {
OkapiUI okapiUi = new OkapiUI();
okapiUi.setVisible(true);
} else {
int returnValue;
returnValue = commandLine(settings);
if (returnValue != 0) {
System.out.println("An error occurred");
}
}
}
|
java
|
{
"resource": ""
}
|
q3896
|
MaxiCode.getPrimaryCodewords
|
train
|
private int[] getPrimaryCodewords() {
assert mode == 2 || mode == 3;
if (primaryData.length() != 15) {
throw new OkapiException("Invalid Primary String");
}
for (int i = 9; i < 15; i++) { /* check that country code and service are numeric */
if (primaryData.charAt(i) < '0' || primaryData.charAt(i) > '9') {
throw new OkapiException("Invalid Primary String");
}
}
String postcode;
if (mode == 2) {
postcode = primaryData.substring(0, 9);
int index = postcode.indexOf(' ');
if (index != -1) {
postcode = postcode.substring(0, index);
}
} else {
// if (mode == 3)
postcode = primaryData.substring(0, 6);
}
int country = Integer.parseInt(primaryData.substring(9, 12));
int service = Integer.parseInt(primaryData.substring(12, 15));
if (debug) {
System.out.println("Using mode " + mode);
System.out.println(" Postcode: " + postcode);
System.out.println(" Country Code: " + country);
System.out.println(" Service: " + service);
}
if (mode == 2) {
return getMode2PrimaryCodewords(postcode, country, service);
} else { // mode == 3
return getMode3PrimaryCodewords(postcode, country, service);
}
}
|
java
|
{
"resource": ""
}
|
q3897
|
MaxiCode.getMode2PrimaryCodewords
|
train
|
private static int[] getMode2PrimaryCodewords(String postcode, int country, int service) {
for (int i = 0; i < postcode.length(); i++) {
if (postcode.charAt(i) < '0' || postcode.charAt(i) > '9') {
postcode = postcode.substring(0, i);
break;
}
}
int postcodeNum = Integer.parseInt(postcode);
int[] primary = new int[10];
primary[0] = ((postcodeNum & 0x03) << 4) | 2;
primary[1] = ((postcodeNum & 0xfc) >> 2);
primary[2] = ((postcodeNum & 0x3f00) >> 8);
primary[3] = ((postcodeNum & 0xfc000) >> 14);
primary[4] = ((postcodeNum & 0x3f00000) >> 20);
primary[5] = ((postcodeNum & 0x3c000000) >> 26) | ((postcode.length() & 0x3) << 4);
primary[6] = ((postcode.length() & 0x3c) >> 2) | ((country & 0x3) << 4);
primary[7] = (country & 0xfc) >> 2;
primary[8] = ((country & 0x300) >> 8) | ((service & 0xf) << 2);
primary[9] = ((service & 0x3f0) >> 4);
return primary;
}
|
java
|
{
"resource": ""
}
|
q3898
|
MaxiCode.getMode3PrimaryCodewords
|
train
|
private static int[] getMode3PrimaryCodewords(String postcode, int country, int service) {
int[] postcodeNums = new int[postcode.length()];
postcode = postcode.toUpperCase();
for (int i = 0; i < postcodeNums.length; i++) {
postcodeNums[i] = postcode.charAt(i);
if (postcode.charAt(i) >= 'A' && postcode.charAt(i) <= 'Z') {
// (Capital) letters shifted to Code Set A values
postcodeNums[i] -= 64;
}
if (postcodeNums[i] == 27 || postcodeNums[i] == 31 || postcodeNums[i] == 33 || postcodeNums[i] >= 59) {
// Not a valid postal code character, use space instead
postcodeNums[i] = 32;
}
// Input characters lower than 27 (NUL - SUB) in postal code are interpreted as capital
// letters in Code Set A (e.g. LF becomes 'J')
}
int[] primary = new int[10];
primary[0] = ((postcodeNums[5] & 0x03) << 4) | 3;
primary[1] = ((postcodeNums[4] & 0x03) << 4) | ((postcodeNums[5] & 0x3c) >> 2);
primary[2] = ((postcodeNums[3] & 0x03) << 4) | ((postcodeNums[4] & 0x3c) >> 2);
primary[3] = ((postcodeNums[2] & 0x03) << 4) | ((postcodeNums[3] & 0x3c) >> 2);
primary[4] = ((postcodeNums[1] & 0x03) << 4) | ((postcodeNums[2] & 0x3c) >> 2);
primary[5] = ((postcodeNums[0] & 0x03) << 4) | ((postcodeNums[1] & 0x3c) >> 2);
primary[6] = ((postcodeNums[0] & 0x3c) >> 2) | ((country & 0x3) << 4);
primary[7] = (country & 0xfc) >> 2;
primary[8] = ((country & 0x300) >> 8) | ((service & 0xf) << 2);
primary[9] = ((service & 0x3f0) >> 4);
return primary;
}
|
java
|
{
"resource": ""
}
|
q3899
|
MaxiCode.bestSurroundingSet
|
train
|
private int bestSurroundingSet(int index, int length, int... valid) {
int option1 = set[index - 1];
if (index + 1 < length) {
// we have two options to check
int option2 = set[index + 1];
if (contains(valid, option1) && contains(valid, option2)) {
return Math.min(option1, option2);
} else if (contains(valid, option1)) {
return option1;
} else if (contains(valid, option2)) {
return option2;
} else {
return valid[0];
}
} else {
// we only have one option to check
if (contains(valid, option1)) {
return option1;
} else {
return valid[0];
}
}
}
|
java
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.