index int64 0 0 | repo_id stringlengths 9 205 | file_path stringlengths 31 246 | content stringlengths 1 12.2M | __index_level_0__ int64 0 10k |
|---|---|---|---|---|
0 | Create_ds/axis-axis2-java-savan/modules/core/src/main/java/org/apache | Create_ds/axis-axis2-java-savan/modules/core/src/main/java/org/apache/savan/SavanConstants.java | /*
* Copyright 1999-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.savan;
/** Contains the constants used by Savan */
public interface SavanConstants {
String CONFIGURATION_MANAGER =
"SavanConfigurationManager"; //Property name to store the CM in the ConfigCtx.
String VALUE_TRUE = "true";
String VALUE_FALSE = "false";
String MESSAGE_TYPE = "SavanMessageType";
String PUBLICATION_MESSAGE = "SavanPublicationMessage";
String SUBSCRIBER_STORE = "SubscriberStore"; //AxisService property
String SUBSCRIBER_STORE_KEY = "SubscriberStoreKey"; //to mention the key in the services.xml
String PROTOCOL = "Protocol";
String CONFIG_FILE = "savan-config.xml";
String UTIL_FACTORY = "UtilFactory";
String DEFAULT_SUBSCRIBER_STORE_KEY = "default";
interface MessageTypes {
int UNKNOWN = -1;
int SUBSCRIPTION_MESSAGE = 1;
int SUBSCRIPTION_RESPONSE_MESSAGE = 2;
int UNSUBSCRIPTION_MESSAGE = 3;
int UNSUBSCRIPTION_RESPONSE_MESSAGE = 4;
int RENEW_MESSAGE = 5;
int RENEW_RESPONSE_MESSAGE = 6;
int GET_STATUS_MESSAGE = 7;
int GET_STATUS_RESPONSE_MESSAGE = 8;
int PUBLISH = 9;
}
interface Properties {
String SUBSCRIBER_STORE = "SubscriberStore";
}
}
| 6,300 |
0 | Create_ds/axis-axis2-java-savan/modules/core/src/main/java/org/apache | Create_ds/axis-axis2-java-savan/modules/core/src/main/java/org/apache/savan/MessageInitializer.java | /*
* Copyright 1999-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.savan;
public class MessageInitializer {
public static void initializeMessage(SavanMessageContext smc) {
//TODO fill the properties in to the SMC,
//For e.g. UtilFactory and the SubscriberStore
}
}
| 6,301 |
0 | Create_ds/axis-axis2-java-savan/modules/core/src/main/java/org/apache | Create_ds/axis-axis2-java-savan/modules/core/src/main/java/org/apache/savan/SavanMessageContext.java | /*
* Copyright 1999-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.savan;
import org.apache.axiom.soap.SOAPEnvelope;
import org.apache.axis2.AxisFault;
import org.apache.axis2.context.ConfigurationContext;
import org.apache.axis2.context.MessageContext;
import org.apache.axis2.description.Parameter;
import org.apache.savan.configuration.Protocol;
import org.apache.savan.storage.SubscriberStore;
/**
* This encaptulates a Axis2 Message Context. Provide some easy methods to access Savan specific
* properties easily.
*/
public class SavanMessageContext {
MessageContext messageContext = null;
public SavanMessageContext(MessageContext messageContext) {
this.messageContext = messageContext;
}
public void setMessageType(int type) {
messageContext.setProperty(SavanConstants.MESSAGE_TYPE, type);
}
public int getMessageType() {
Integer typeInt = (Integer)messageContext.getProperty(SavanConstants.MESSAGE_TYPE);
if (typeInt == null) {
typeInt = SavanConstants.MessageTypes.UNKNOWN;
messageContext.setProperty(SavanConstants.MESSAGE_TYPE, typeInt);
}
return typeInt;
}
public ConfigurationContext getConfigurationContext() {
return messageContext.getConfigurationContext();
}
public Object getProperty(String key) {
return messageContext.getProperty(key);
}
public void setProperty(String key, Object val) {
messageContext.setProperty(key, val);
}
public SOAPEnvelope getEnvelope() {
return messageContext.getEnvelope();
}
public MessageContext getMessageContext() {
return messageContext;
}
public SubscriberStore getSubscriberStore() {
Parameter parameter = messageContext.getParameter(SavanConstants.SUBSCRIBER_STORE);
SubscriberStore subscriberStore = null;
if (parameter != null) {
parameter = messageContext.getParameter(SavanConstants.SUBSCRIBER_STORE);
subscriberStore = (SubscriberStore)parameter.getValue();
}
return subscriberStore;
}
public void setSubscriberStore(SubscriberStore store) throws SavanException {
Parameter parameter = new Parameter();
parameter.setName(SavanConstants.SUBSCRIBER_STORE);
parameter.setValue(store);
try {
messageContext.getAxisService().addParameter(parameter);
} catch (AxisFault e) {
String message = "Could not add the AbstractSubscriber Store parameter";
throw new SavanException(message, e);
}
}
public void setProtocol(Protocol protocol) {
messageContext.setProperty(SavanConstants.PROTOCOL, protocol);
}
public Protocol getProtocol() {
return (Protocol)messageContext.getProperty(SavanConstants.PROTOCOL);
}
}
| 6,302 |
0 | Create_ds/axis-axis2-java-savan/modules/core/src/main/java/org/apache | Create_ds/axis-axis2-java-savan/modules/core/src/main/java/org/apache/savan/SavanException.java | /*
* Copyright 1999-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.savan;
import org.apache.axis2.AxisFault;
/** To convey a exception that occured in Savan. */
public class SavanException extends AxisFault {
public SavanException(String cause) {
super(cause);
}
public SavanException(String cause, Exception superException) {
super(cause, superException);
}
public SavanException(Exception superException) {
super(superException);
}
}
| 6,303 |
0 | Create_ds/axis-axis2-java-savan/modules/core/src/main/java/org/apache/savan | Create_ds/axis-axis2-java-savan/modules/core/src/main/java/org/apache/savan/filters/XPathBasedFilter.java | /*
* Copyright 1999-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.savan.filters;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMNode;
import org.apache.axiom.om.OMText;
import org.apache.axiom.om.xpath.AXIOMXPath;
import org.apache.savan.SavanException;
import org.jaxen.JaxenException;
import java.util.List;
/** A filter that does filtering of messages based on a XPath string. */
public class XPathBasedFilter implements Filter {
public static String XPATH_BASED_FILTER = "http://www.w3.org/TR/1999/REC-xpath-19991116";
private String XPathString = null;
public String getXPathString() {
return XPathString;
}
public void setXPathString(String XPathString) {
this.XPathString = XPathString;
}
/** This method may fail due to the JIRA issues WS-Commons(40) amd WS-Commons (41) */
public boolean checkCompliance(OMElement element) throws SavanException {
if (XPathString == null)
return true;
try {
AXIOMXPath xpath = new AXIOMXPath(XPathString);
List resultList = xpath.selectNodes(element);
return resultList.size() > 0;
} catch (JaxenException e) {
throw new SavanException(e);
}
}
public void setUp(OMNode element) {
if (!(element instanceof OMText))
throw new IllegalArgumentException("Cannot determine a valid XPath string");
OMText text = (OMText)element;
XPathString = text.getText();
}
public Object getFilterValue() {
return XPathString;
}
}
| 6,304 |
0 | Create_ds/axis-axis2-java-savan/modules/core/src/main/java/org/apache/savan | Create_ds/axis-axis2-java-savan/modules/core/src/main/java/org/apache/savan/filters/EmptyFilter.java | /*
* Copyright 2004,2005 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.savan.filters;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMNode;
import org.apache.savan.SavanException;
/** This filter does not do any affective filtering. May be the default for some protocols. */
public class EmptyFilter implements Filter {
public boolean checkCompliance(OMElement envelope) throws SavanException {
return true;
}
public Object getFilterValue() {
return null;
}
public void setUp(OMNode element) {
}
}
| 6,305 |
0 | Create_ds/axis-axis2-java-savan/modules/core/src/main/java/org/apache/savan | Create_ds/axis-axis2-java-savan/modules/core/src/main/java/org/apache/savan/filters/Filter.java | /*
* Copyright 1999-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.savan.filters;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMNode;
import org.apache.savan.SavanException;
/** Defines a filter used by Savan. */
public interface Filter {
/**
* To check weather the passed envelope is compliant with the current filter.
*
* @param envelope
* @return
* @throws SavanException
*/
public boolean checkCompliance(OMElement element) throws SavanException;
/**
* To initialize the filter. The filter value should be sent to the argument (for e.g. As a OMText
* for a String)
*
* @param element
*/
public void setUp(OMNode element);
/**
* Returns a previously set filter value.
*
* @return
*/
public Object getFilterValue ();
}
| 6,306 |
0 | Create_ds/axis-axis2-java-savan/modules/core/src/main/java/org/apache/savan | Create_ds/axis-axis2-java-savan/modules/core/src/main/java/org/apache/savan/configuration/ConfigurationManager.java | /*
* Copyright 1999-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.savan.configuration;
import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMFactory;
import org.apache.axiom.om.impl.builder.StAXOMBuilder;
import org.apache.axiom.om.impl.llom.factory.OMXMLBuilderFactory;
import org.apache.savan.SavanConstants;
import org.apache.savan.SavanException;
import org.apache.savan.filters.Filter;
import org.apache.savan.storage.SubscriberStore;
import org.apache.savan.subscribers.Subscriber;
import org.apache.savan.util.UtilFactory;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/**
* This is responsible for loading Savan configuration data from a resource for e.g. from a
* savan-config.xml fie
*/
public class ConfigurationManager {
private HashMap protocolMap = null;
private HashMap subscriberStoreNamesMap = null;
private HashMap filterMap = null;
private HashMap subscribersMap = null;
private final String SAVAN_CONFIG = "savan-config";
private final String PROTOCOLS = "protocols";
private final String PROTOCOL = "protocol";
private final String NAME = "name";
private final String UTIL_FACTORY = "utilFactory";
private final String MAPPING_RULES = "mapping-rules";
private final String ACTION = "action";
private final String SUBSCRIBER_STORES = "subscriberStores";
private final String SUBSCRIBER_STORE = "subscriberStore";
private final String FILTERS = "filters";
private final String FILTER = "filter";
private final String KEY = "key";
private final String CLASS = "class";
private final String IDENTIFIER = "identifier";
private final String SUBSCRIBERS = "subscribers";
private final String SUBSCRIBER = "subscriber";
private final String URL_APPENDER = "urlAppender";
private final String DEFAULT_SUBSCRIBER = "defaultSubscriber";
private final String DEFAULT_FILTER = "defaultFilter";
public ConfigurationManager() {
protocolMap = new HashMap();
subscriberStoreNamesMap = new HashMap();
filterMap = new HashMap();
subscribersMap = new HashMap();
}
/**
* To load configurations from a savan-config.xml file in the classpath.
*
* @throws SavanException
*/
public void configure() throws SavanException {
ClassLoader classLoader = getClass().getClassLoader();
configure(classLoader);
}
public void configure(ClassLoader classLoader) throws SavanException {
InputStream in = classLoader.getResourceAsStream(SavanConstants.CONFIG_FILE);
if (in == null)
throw new SavanException(
"Cannot find the savan configuration file. Initialation cannot continue.");
configure(in);
}
/**
* To Load configurations from a file.
*
* @param file
* @throws SavanException
*/
public void configure(File file) throws SavanException {
try {
InputStream in = new FileInputStream(file);
configure(in);
} catch (IOException e) {
throw new SavanException(e);
}
}
/**
* To load configurations from a InputStream.
*
* @param in
* @throws SavanException
*/
public void configure(InputStream in) throws SavanException {
if (in == null) {
String message = "Invalid InputStream.";
throw new SavanException(message);
}
try {
XMLStreamReader parser = XMLInputFactory.newInstance().createXMLStreamReader(in);
OMFactory factory = OMAbstractFactory.getOMFactory();
StAXOMBuilder builder = OMXMLBuilderFactory.createStAXOMBuilder(factory, parser);
OMElement document = builder.getDocumentElement();
if (document == null) {
throw new SavanException("Configuration XML does not have a document element");
}
processSavanConfig(document);
} catch (Exception e) {
throw new SavanException(e);
}
}
private void processSavanConfig(OMElement element) throws SavanException {
if (!SAVAN_CONFIG.equals(element.getLocalName())) {
throw new SavanException(
"'savan-config'should be the document element of the savan configuration xml file");
}
OMElement protocolsElement = element.getFirstChildWithName(new QName(PROTOCOLS));
if (protocolsElement == null) {
throw new SavanException(
"'protocols' element should be present, as a sub-element of the 'savan-config' element");
}
processProtocols(protocolsElement);
OMElement subscriberStoresElement =
element.getFirstChildWithName(new QName(SUBSCRIBER_STORES));
if (subscriberStoresElement == null) {
throw new SavanException(
"'subscriberStores' element should be present, as a sub-element of the 'savan-config' element");
}
processSubscriberStores(subscriberStoresElement);
OMElement filtersElement = element.getFirstChildWithName(new QName(FILTERS));
if (subscriberStoresElement == null) {
throw new SavanException(
"'Filters' element should be present, as a sub-element of the 'savan-config' element");
}
processFilters(filtersElement);
OMElement subscribersElement = element.getFirstChildWithName(new QName(SUBSCRIBERS));
if (subscriberStoresElement == null) {
throw new SavanException(
"'Subscribers' element should be present as a sub-element of the 'savan-config' element");
}
processSubscribers(subscribersElement);
}
private void processProtocols(OMElement element) throws SavanException {
Iterator protocolElementsIterator = element.getChildrenWithName(new QName(PROTOCOL));
while (protocolElementsIterator.hasNext()) {
OMElement protocolElement = (OMElement)protocolElementsIterator.next();
processProtocol(protocolElement);
}
}
private void processProtocol(OMElement element) throws SavanException {
Protocol protocol = new Protocol();
OMElement nameElement = element.getFirstChildWithName(new QName(NAME));
if (nameElement == null)
throw new SavanException("Protocol must have a 'Name' subelement");
String name = nameElement.getText();
protocol.setName(name);
OMElement utilFactoryNameElement = element.getFirstChildWithName(new QName(UTIL_FACTORY));
if (utilFactoryNameElement == null)
throw new SavanException("Protocol must have a 'UtilFactory' subelement");
String utilFactoryName = utilFactoryNameElement.getText();
Object obj = getObject(utilFactoryName);
if (!(obj instanceof UtilFactory))
throw new SavanException("UtilFactory element" + utilFactoryName +
"is not a subtype of the UtilFactory class");
protocol.setUtilFactory((UtilFactory)obj);
OMElement mappingRulesElement = element.getFirstChildWithName(new QName(MAPPING_RULES));
if (mappingRulesElement == null)
throw new SavanException("Protocol must have a 'mappingRules' sub-element");
processMappingRules(mappingRulesElement, protocol);
OMElement defaultSubscriberElement =
element.getFirstChildWithName(new QName(DEFAULT_SUBSCRIBER));
if (defaultSubscriberElement == null)
throw new SavanException("Protocols must have a 'defaultSubscriber' sub-element");
String defaultSubscriber = defaultSubscriberElement.getText();
protocol.setDefaultSubscriber(defaultSubscriber);
OMElement defaultFilterElement = element.getFirstChildWithName(new QName(DEFAULT_FILTER));
if (defaultFilterElement == null)
throw new SavanException("Protocols must have a 'defaultFilter' sub-element");
String defaultFilter = defaultFilterElement.getText();
protocol.setDefaultFilter(defaultFilter);
protocolMap.put(protocol.getName(), protocol);
}
private void processMappingRules(OMElement element, Protocol protocol) {
MappingRules mappingRules = protocol.getMappingRules();
Iterator actionsIterator = element.getChildrenWithName(new QName(ACTION));
while (actionsIterator.hasNext()) {
OMElement actionElement = (OMElement)actionsIterator.next();
String action = actionElement.getText();
mappingRules.addRule(MappingRules.MAPPING_TYPE_ACTION, action);
}
}
private void processSubscriberStores(OMElement element) throws SavanException {
Iterator subscriberStoreElementsIterator =
element.getChildrenWithName(new QName(SUBSCRIBER_STORE));
while (subscriberStoreElementsIterator.hasNext()) {
OMElement subscriberStoreElement = (OMElement)subscriberStoreElementsIterator.next();
processSubscriberStore(subscriberStoreElement);
}
}
private void processSubscriberStore(OMElement element) throws SavanException {
OMElement keyElement = element.getFirstChildWithName(new QName(KEY));
if (keyElement == null)
throw new SavanException("SubscriberStore must have a 'key' subelement");
String key = keyElement.getText();
OMElement classElement = element.getFirstChildWithName(new QName(CLASS));
if (classElement == null)
throw new SavanException("SubscriberStore must have a 'Clazz' subelement'");
String clazz = classElement.getText();
//initialize the class to check weather it is value
Object obj = getObject(clazz);
if (!(obj instanceof SubscriberStore)) {
String message =
"Class " + clazz + " does not implement the SubscriberStore interface.";
throw new SavanException(message);
}
subscriberStoreNamesMap.put(key, clazz);
}
public HashMap getProtocolMap() {
return protocolMap;
}
public Protocol getProtocol(String name) {
return (Protocol)protocolMap.get(name);
}
public SubscriberStore getSubscriberStoreInstance(String key) throws SavanException {
String name = (String)subscriberStoreNamesMap.get(key);
return (SubscriberStore)getObject(name);
}
public Filter getFilterInstanceFromName(String name) throws SavanException {
for (Iterator it = filterMap.keySet().iterator(); it.hasNext();) {
String key = (String)it.next();
FilterBean filterBean = (FilterBean)filterMap.get(key);
if (name.equals(filterBean.getName()))
return (Filter)getObject(filterBean.getClazz());
}
return null;
}
public Filter getFilterInstanceFromId(String id) throws SavanException {
FilterBean filterBean = (FilterBean)filterMap.get(id);
String filterClass = filterBean.getClazz();
if (filterClass == null)
return null;
return (Filter)getObject(filterClass);
}
private Object getObject(String className) throws SavanException {
Object obj;
try {
Class c = Class.forName(className);
obj = c.newInstance();
} catch (Exception e) {
String message = "Can't instantiate the class:" + className;
throw new SavanException(message, e);
}
return obj;
}
private void processFilters(OMElement element) throws SavanException {
Iterator filterElementsIterator = element.getChildrenWithName(new QName(FILTER));
while (filterElementsIterator.hasNext()) {
OMElement filterElement = (OMElement)filterElementsIterator.next();
processFilter(filterElement);
}
}
private void processFilter(OMElement element) throws SavanException {
OMElement nameElement = element.getFirstChildWithName(new QName(NAME));
OMElement identifierElement = element.getFirstChildWithName(new QName(IDENTIFIER));
OMElement classElement = element.getFirstChildWithName(new QName(CLASS));
if (nameElement == null)
throw new SavanException("Name element is not present within the Filter");
if (identifierElement == null)
throw new SavanException("Identifier element is not present within the Filter");
if (classElement == null)
throw new SavanException("Class element is not present within the Filter");
String name = nameElement.getText();
String identifier = identifierElement.getText();
String clazz = classElement.getText();
//initialize the class to check weather it is value
Object obj = getObject(clazz);
if (!(obj instanceof Filter)) {
String message = "Class " + clazz + " does not implement the Filter interface.";
throw new SavanException(message);
}
FilterBean bean = new FilterBean();
bean.setName(name);
bean.setIdentifier(identifier);
bean.setClazz(clazz);
filterMap.put(identifier, bean);
}
private void processSubscribers(OMElement element) throws SavanException {
Iterator subscriberElementsIterator = element.getChildrenWithName(new QName(SUBSCRIBER));
while (subscriberElementsIterator.hasNext()) {
OMElement subscriberElement = (OMElement)subscriberElementsIterator.next();
processSubscriber(subscriberElement);
}
}
private void processSubscriber(OMElement element) throws SavanException {
OMElement nameElement = element.getFirstChildWithName(new QName(NAME));
OMElement urlAppenderElement = element.getFirstChildWithName(new QName(URL_APPENDER));
OMElement classElement = element.getFirstChildWithName(new QName(CLASS));
if (nameElement == null)
throw new SavanException("Name element is not present within the AbstractSubscriber");
if (classElement == null)
throw new SavanException("Class element is not present within the Filter");
String name = nameElement.getText();
String clazz = classElement.getText();
//initialize the class to check weather it is valid
Object obj = getObject(clazz);
if (!(obj instanceof Subscriber)) {
String message = "Class " + clazz + " does not implement the Subscriber interface.";
throw new SavanException(message);
}
SubscriberBean bean = new SubscriberBean();
bean.setName(name);
bean.setClazz(clazz);
subscribersMap.put(name, bean);
}
public Map getSubscriberBeans() {
return subscribersMap;
}
public Map getFilterBeans() {
return filterMap;
}
public SubscriberBean getSubscriberBean(String subscriberName) {
return (SubscriberBean)subscribersMap.get(subscriberName);
}
public Subscriber getSubscriberInstance(String subscriberName) throws SavanException {
SubscriberBean subscriberBean = (SubscriberBean)subscribersMap.get(subscriberName);
if (subscriberBean == null) {
String message = "A subscriber with the name '" + subscriberName + "' was not found.";
throw new SavanException(message);
}
return (Subscriber)getObject(subscriberBean.getClazz());
}
}
| 6,307 |
0 | Create_ds/axis-axis2-java-savan/modules/core/src/main/java/org/apache/savan | Create_ds/axis-axis2-java-savan/modules/core/src/main/java/org/apache/savan/configuration/Protocol.java | /*
* Copyright 1999-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.savan.configuration;
import org.apache.savan.util.UtilFactory;
/**
* Encapsulates a date of a Protocol as defined by Savan configurations. (probably from a
* savan-config.xml file).
*/
public class Protocol {
private String name;
private UtilFactory utilFactory;
private MappingRules mappingRules;
private String defaultSubscriber;
private String defaultFilter;
public Protocol() {
this.mappingRules = new MappingRules();
}
public String getDefaultFilter() {
return defaultFilter;
}
public String getDefaultSubscriber() {
return defaultSubscriber;
}
public void setDefaultFilter(String defaultFilter) {
this.defaultFilter = defaultFilter;
}
public void setDefaultSubscriber(String defaultSubscriber) {
this.defaultSubscriber = defaultSubscriber;
}
public String getName() {
return name;
}
public UtilFactory getUtilFactory() {
return utilFactory;
}
public void setName(String name) {
this.name = name;
}
public void setUtilFactory(UtilFactory utilFactory) {
this.utilFactory = utilFactory;
}
public MappingRules getMappingRules() {
return mappingRules;
}
}
| 6,308 |
0 | Create_ds/axis-axis2-java-savan/modules/core/src/main/java/org/apache/savan | Create_ds/axis-axis2-java-savan/modules/core/src/main/java/org/apache/savan/configuration/FilterBean.java | /*
* Copyright 2004,2005 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.savan.configuration;
public class FilterBean {
String name;
String identifier;
String clazz;
public String getClazz() {
return clazz;
}
public String getIdentifier() {
return identifier;
}
public String getName() {
return name;
}
public void setClazz(String clazz) {
this.clazz = clazz;
}
public void setIdentifier(String identifier) {
this.identifier = identifier;
}
public void setName(String name) {
this.name = name;
}
}
| 6,309 |
0 | Create_ds/axis-axis2-java-savan/modules/core/src/main/java/org/apache/savan | Create_ds/axis-axis2-java-savan/modules/core/src/main/java/org/apache/savan/configuration/MappingRules.java | /*
* Copyright 1999-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.savan.configuration;
import java.util.ArrayList;
/**
* Encapsulates a date of a set of Mapping-Rules as defined by Savan configurations. (probably from
* a savan-config.xml file).
*/
public class MappingRules {
public static final int MAPPING_TYPE_ACTION = 1;
private ArrayList actionList = null;
public MappingRules() {
actionList = new ArrayList();
}
public void addRule(int type, String value) {
if (type == MAPPING_TYPE_ACTION)
actionList.add(value);
}
public boolean ruleMatched(int type, String value) {
if (type == MAPPING_TYPE_ACTION)
return actionList.contains(value);
return false;
}
}
| 6,310 |
0 | Create_ds/axis-axis2-java-savan/modules/core/src/main/java/org/apache/savan | Create_ds/axis-axis2-java-savan/modules/core/src/main/java/org/apache/savan/configuration/SubscriberBean.java | /*
* Copyright 2004,2005 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.savan.configuration;
public class SubscriberBean {
String name;
String clazz;
public String getClazz() {
return clazz;
}
public String getName() {
return name;
}
public void setClazz(String clazz) {
this.clazz = clazz;
}
public void setName(String name) {
this.name = name;
}
}
| 6,311 |
0 | Create_ds/axis-axis2-java-savan/modules/core/src/main/java/org/apache/savan | Create_ds/axis-axis2-java-savan/modules/core/src/main/java/org/apache/savan/publication/PublicationReport.java | /*
* Copyright 1999-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.savan.publication;
import org.apache.savan.SavanException;
import java.util.ArrayList;
import java.util.Hashtable;
/**
* This will encapsulate error information of a specific publication. Probably will contain details
* of each subscriber to which the message could not be delivered successfully.
*/
public class PublicationReport {
/**
* The susbscribers to which this msg could not be sent. Probably their ID and the Exception that
* occured.
*/
private Hashtable errors = null;
/** Ids of the subscribers to which this msg could be sent successfully. */
private ArrayList notifiedSubscribers;
public PublicationReport() {
errors = new Hashtable();
notifiedSubscribers = new ArrayList();
}
public void addErrorReportEntry(String id, SavanException reason) {
errors.put(id, reason);
}
public void addNotifiedSubscriber(String subscriberID) {
notifiedSubscribers.add(subscriberID);
}
public Hashtable getErrors() {
return errors;
}
public ArrayList getNotifiedSubscribers() {
return notifiedSubscribers;
}
}
| 6,312 |
0 | Create_ds/axis-axis2-java-savan/modules/core/src/main/java/org/apache/savan/publication | Create_ds/axis-axis2-java-savan/modules/core/src/main/java/org/apache/savan/publication/client/PublicationClient.java | /*
* Copyright 1999-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.savan.publication.client;
import org.apache.axiom.om.OMElement;
import org.apache.axis2.AxisFault;
import org.apache.axis2.context.ConfigurationContext;
import org.apache.axis2.description.AxisOperation;
import org.apache.axis2.description.AxisService;
import org.apache.savan.SavanException;
import org.apache.savan.publication.PublicationReport;
import org.apache.savan.storage.SubscriberStore;
import org.apache.savan.subscribers.Subscriber;
import org.apache.savan.subscribers.SubscriberGroup;
import org.apache.savan.util.CommonUtil;
import java.net.URI;
import java.util.Iterator;
/**
* This can be used to make the Publication Process easy. Handle things like engaging the savan
* module correctly and setting the correct subscriber store.
*/
public class PublicationClient {
public static final String TEMP_PUBLICATION_ACTION = "UUID:TempPublicationAction";
private ConfigurationContext configurationContext = null;
public PublicationClient(ConfigurationContext configurationContext) {
this.configurationContext = configurationContext;
}
/**
* This can be used by the Publishers in the same JVM (e.g. a service deployed in the same Axis2
* instance).
*
* @param eventData - The XML message to be published
* @param service - The service to which this publication is bound to (i.e. this will be only
* sent to the subscribers of this service)
* @param eventName - The name of the event, this can be a action which represents an out only
* operation or a Topic ID.
* @throws SavanException
*/
public void sendPublication(OMElement eventData, AxisService service, URI eventName)
throws SavanException {
try {
SubscriberStore subscriberStore = CommonUtil.getSubscriberStore(service);
if (subscriberStore == null)
throw new SavanException("Cannot find the Subscriber Store");
PublicationReport report = new PublicationReport();
if (eventName != null) {
//there should be a valid operation or a SubscriberGroup to match this event.
AxisOperation operation = getAxisOperationFromEventName(eventName);
if (operation != null) {
//send to all subscribers with this operation.
throw new UnsupportedOperationException("Not implemented");
} else {
//there should be a valid SubscriberGroup to match this eventName
String groupId = eventName.toString();
SubscriberGroup group =
(SubscriberGroup)subscriberStore.getSubscriberGroup(groupId);
if (group != null)
group.sendEventDataToGroup(eventData);
else
throw new SavanException(
"Could not find a subscriberGroup or an operation to match the eventName");
}
} else {
//no event name, so send it to everybody.
//sending to all individual subscribers
for (Iterator iter = subscriberStore.retrieveAllSubscribers(); iter.hasNext();) {
Subscriber subscriber = (Subscriber)iter.next();
subscriber.sendEventData(eventData);
}
//sending to all Subscriber Groups
for (Iterator iter = subscriberStore.retrieveAllSubscriberGroups();
iter.hasNext();) {
SubscriberGroup subscriberGroup = (SubscriberGroup)iter.next();
subscriberGroup.sendEventDataToGroup(eventData);
}
}
} catch (AxisFault e) {
String message = "Could not send the publication";
throw new SavanException(message, e);
}
}
private AxisOperation getAxisOperationFromEventName(URI eventName) {
//TODO do operation lookup
return null;
}
}
| 6,313 |
0 | Create_ds/axis-axis2-java-savan/modules/core/src/main/java/org/apache/savan | Create_ds/axis-axis2-java-savan/modules/core/src/main/java/org/apache/savan/util/CommonUtil.java | /*
* Copyright 1999-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.savan.util;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.impl.llom.factory.OMXMLBuilderFactory;
import org.apache.axiom.soap.SOAPEnvelope;
import org.apache.axiom.soap.SOAPFactory;
import org.apache.axiom.soap.impl.builder.StAXSOAPModelBuilder;
import org.apache.axis2.databinding.types.Duration;
import org.apache.axis2.description.AxisService;
import org.apache.axis2.description.Parameter;
import org.apache.savan.SavanConstants;
import org.apache.savan.storage.SubscriberStore;
import org.apache.xmlbeans.XmlObject;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Calendar;
/** A common set of methods that may be used in various places of Savan. */
public class CommonUtil {
public static Calendar addDurationToCalendar(Calendar calendar, Duration duration) {
calendar.add(Calendar.YEAR, duration.getYears());
calendar.add(Calendar.MONTH, duration.getMonths());
calendar.add(Calendar.DATE, duration.getDays());
calendar.add(Calendar.HOUR, duration.getHours());
calendar.add(Calendar.MINUTE, duration.getMinutes());
calendar.add(Calendar.SECOND, (int)duration.getSeconds());
return calendar;
}
/**
* Will be used by test cases to load XML files from test-resources as Envelopes SOAP 1.1 is
* assumed
*
* @param path
* @param name
* @return
*/
public static SOAPEnvelope getTestEnvelopeFromFile(String path,
String name,
SOAPFactory factory) throws IOException {
try {
String fullName = path + File.separator + name;
FileReader reader = new FileReader(fullName);
XMLStreamReader streamReader = XMLInputFactory.newInstance().createXMLStreamReader(
reader);
StAXSOAPModelBuilder builder = OMXMLBuilderFactory.createStAXSOAPModelBuilder(
factory, streamReader);
return builder.getSOAPEnvelope();
} catch (XMLStreamException e) {
throw new RuntimeException(e);
}
}
public static boolean isDuration(String timeStr) {
return timeStr.startsWith("p") || timeStr.startsWith("P") || timeStr.startsWith("-p") ||
timeStr.startsWith("-P");
}
public static SubscriberStore getSubscriberStore(AxisService axisService) {
Parameter parameter = axisService.getParameter(SavanConstants.SUBSCRIBER_STORE);
if (parameter == null)
return null;
return (SubscriberStore)parameter.getValue();
}
public static OMElement toOM(XmlObject element) {
org.apache.axiom.om.impl.builder.StAXOMBuilder builder =
new org.apache.axiom.om.impl.builder.StAXOMBuilder
(org.apache.axiom.om.OMAbstractFactory.getOMFactory(),
new org.apache.axis2.util.StreamWrapper(element.newXMLStreamReader()));
return builder.getDocumentElement();
}
}
| 6,314 |
0 | Create_ds/axis-axis2-java-savan/modules/core/src/main/java/org/apache/savan | Create_ds/axis-axis2-java-savan/modules/core/src/main/java/org/apache/savan/util/UtilFactory.java | /*
* Copyright 1999-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.savan.util;
import org.apache.savan.SavanMessageContext;
import org.apache.savan.messagereceiver.MessageReceiverDelegator;
import org.apache.savan.subscription.SubscriptionProcessor;
/**
* Defines a Utility Factory in Savan. Each Protocol will provide its own set of utilities. These
* utilities will be used in various levels in Savan.
*/
public interface UtilFactory {
public abstract SavanMessageContext initializeMessage(SavanMessageContext messageContext);
public abstract SubscriptionProcessor createSubscriptionProcessor();
public abstract MessageReceiverDelegator createMessageReceiverDelegator();
}
| 6,315 |
0 | Create_ds/axis-axis2-java-savan/modules/core/src/main/java/org/apache/savan | Create_ds/axis-axis2-java-savan/modules/core/src/main/java/org/apache/savan/util/ProtocolManager.java | /*
* Copyright 1999-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.savan.util;
import org.apache.savan.SavanConstants;
import org.apache.savan.SavanException;
import org.apache.savan.SavanMessageContext;
import org.apache.savan.configuration.ConfigurationManager;
import org.apache.savan.configuration.MappingRules;
import org.apache.savan.configuration.Protocol;
import java.util.HashMap;
import java.util.Iterator;
/** Utility class to extract the Protocol type from a MessageContext */
public class ProtocolManager {
public static Protocol getMessageProtocol(SavanMessageContext smc) throws SavanException {
//TODO to this depending on Protocol rules. //TODO make this algorithm efficient
ConfigurationManager configurationManager = (ConfigurationManager)smc
.getConfigurationContext().getProperty(SavanConstants.CONFIGURATION_MANAGER);
if (configurationManager == null)
throw new SavanException("Cant find the Configuration Manager");
String action = smc.getMessageContext().getOptions().getAction();
if (action != null) {
HashMap map = configurationManager.getProtocolMap();
Iterator iter = map.values().iterator();
while (iter.hasNext()) {
Protocol protocol = (Protocol)iter.next();
MappingRules mappingRules = protocol.getMappingRules();
if (mappingRules.ruleMatched(MappingRules.MAPPING_TYPE_ACTION, action)) {
return protocol;
}
}
}
return null;
}
}
| 6,316 |
0 | Create_ds/axis-axis2-java-savan/modules/core/src/main/java/org/apache/savan | Create_ds/axis-axis2-java-savan/modules/core/src/main/java/org/apache/savan/atom/Feed.java | package org.apache.savan.atom;
import org.apache.axiom.om.*;
import javax.xml.stream.XMLStreamException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
public class Feed {
private String title;
private String id;
private Date lastUpdated;
private String author;
private ArrayList entries;
private OMDocument document;
private int entryCount;
private OMFactory factory;
private OMNamespace atomNs;
// <feed xmlns="http://www.w3.org/2005/Atom">
// <id>http://www.example.org/myfeed</id>
// <title>My Podcast Feed</title>
// <updated>2005-07-15T12:00:00Z</updated>
// <author>
// <name>James M Snell</name>
// </author>
// <link href="http://example.org" />
// <link rel="self" href="http://example.org/myfeed" />
// <entry>
// <id>http://www.example.org/entries/1</id>
// <title>Atom 1.0</title>
// <updated>2005-07-15T12:00:00Z</updated>
// <link href="http://www.example.org/entries/1" />
// <summary>An overview of Atom 1.0</summary>
// <link rel="enclosure"
// type="audio/mpeg"
// title="MP3"
// href="http://www.example.org/myaudiofile.mp3"
// length="1234" />
// <link rel="enclosure"
// type="application/x-bittorrent"
// title="BitTorrent"
// href="http://www.example.org/myaudiofile.torrent"
// length="1234" />
// <content type="xml">
// ..
// </content>
// </entry>
// </feed>
public Feed(String title, String id, String author, Date lastUpdated) {
this.title = title;
if (title != null) {
title = title.trim();
}
if (author != null) {
author = author.trim();
}
this.id = id;
this.author = author;
if (lastUpdated == null) {
lastUpdated = new Date();
}
factory = OMAbstractFactory.getOMFactory();
document = factory.createOMDocument();
atomNs = factory.createOMNamespace(AtomConstants.ATOM_NAMESPACE, AtomConstants.ATOM_PREFIX);
OMElement feedEle = factory.createOMElement("feed", atomNs, document);
factory.createOMElement("id", atomNs, feedEle).setText(id);
if (title != null) {
factory.createOMElement("title", atomNs, feedEle).setText(title);
}
factory.createOMElement("updated", atomNs, feedEle)
.setText(new SimpleDateFormat("dd-mm-yy'T1'HH:MM:ssZ").format(lastUpdated));
if (author != null) {
OMElement authorEle = factory.createOMElement("author", atomNs, feedEle);
factory.createOMElement("name", atomNs, authorEle).setText(author);
}
}
public void addEntry(OMElement entry) {
entryCount++;
lastUpdated = new Date();
OMElement entryEle =
factory.createOMElement("entry", atomNs, document.getOMDocumentElement());
factory.createOMElement("id", atomNs, entryEle).setText(id + "/" + entryCount);
factory.createOMElement("title", atomNs, entryEle).setText("entry" + entryCount);
factory.createOMElement("updated", atomNs, entryEle)
.setText(new SimpleDateFormat("dd-mm-yy'T1'HH:MM:ssZ").format(lastUpdated));
OMElement contentEle = factory.createOMElement("content", atomNs, entryEle);
contentEle.addAttribute("type", "text/xml", null);
contentEle.addChild(entry);
document.getOMDocumentElement().addChild(entryEle);
}
public void write(OutputStream out) throws XMLStreamException {
document.serialize(out);
}
// public static void main(String[] args) throws Exception{
// Feed feed = new Feed("testtitle","test_id","john");
// StAXOMBuilder builder = new StAXOMBuilder(new ByteArrayInputStream("<foo>bar</foo>".getBytes()));
// feed.addEntry(builder.getDocumentElement());
// feed.write(System.out);
// System.out.flush();
//
// }
public OMElement getFeedAsXml() {
return document.getOMDocumentElement();
}
public OMFactory getFactory() {
return factory;
}
}
| 6,317 |
0 | Create_ds/axis-axis2-java-savan/modules/core/src/main/java/org/apache/savan | Create_ds/axis-axis2-java-savan/modules/core/src/main/java/org/apache/savan/atom/AtomMessageReceiver.java | package org.apache.savan.atom;
import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMException;
import org.apache.axiom.soap.*;
import org.apache.axis2.AxisFault;
import org.apache.axis2.context.MessageContext;
import org.apache.axis2.engine.AxisEngine;
import org.apache.axis2.engine.MessageReceiver;
import org.apache.axis2.i18n.Messages;
import org.apache.axis2.transport.http.HTTPConstants;
import org.apache.axis2.util.MessageContextBuilder;
import org.apache.savan.storage.SubscriberStore;
import org.apache.savan.util.CommonUtil;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
/**
* Handle the HTTP GET requests for feeds
*
* @author Srinath Perera(hemapani@apache.org)
*/
public class AtomMessageReceiver implements MessageReceiver {
public static final String ATOM_NAME = "atom";
public void receive(MessageContext messageCtx) throws AxisFault {
try {
//String resourcePath = messageCtx.getTo().getAddress();
//http://127.0.0.1:5555/axis2/services/PublisherService/atom?a=urn_uuid_96C2CB953DABC98DFC1179904343537.atom
HttpServletRequest request = (HttpServletRequest)messageCtx
.getProperty(HTTPConstants.MC_HTTP_SERVLETREQUEST);
if (request == null || HTTPConstants.HEADER_GET.equals(request.getMethod()) ||
HTTPConstants.HEADER_POST.equals(request.getMethod())) {
SOAPEnvelope envlope = messageCtx.getEnvelope();
OMElement bodyContent = envlope.getBody().getFirstElement();
OMElement feedID = bodyContent.getFirstElement();
String feedIDAsUrn = feedID.getText().replaceAll("_", ":").replaceAll(".atom", "");
SubscriberStore store = CommonUtil.getSubscriberStore(messageCtx.getAxisService());
if (store == null)
throw new AxisFault("Cant find the Savan subscriber store");
AtomSubscriber subscriber = (AtomSubscriber)store.retrieve(feedIDAsUrn);
SOAPFactory fac = getSOAPFactory(messageCtx);
SOAPEnvelope envelope = fac.getDefaultEnvelope();
OMElement result = subscriber.getFeedAsXml();
// String pathWRTRepository = "atom/"+feedID.getText();
//
// File atomFile = messageCtx.getConfigurationContext().getRealPath(pathWRTRepository);
// if(pathWRTRepository.equals("atom/all.atom") && !atomFile.exists()){
// AtomSubscriber atomSubscriber = new AtomSubscriber();
// atomSubscriber.setId(new URI("All"));
// atomSubscriber.setAtomFile(atomFile);
// atomSubscriber.setAuthor("DefaultUser");
// atomSubscriber.setTitle("default Feed");
//
// String serviceAddress = messageCtx.getTo().getAddress();
// int cutIndex = serviceAddress.indexOf("services");
// if(cutIndex > 0){
// serviceAddress = serviceAddress.substring(0,cutIndex-1);
// }
// atomSubscriber.setFeedUrl(serviceAddress+"/services/"+messageCtx.getServiceContext().getAxisService().getName() +"/atom?feed=all.atom");
//
//
// SubscriberStore store = CommonUtil.getSubscriberStore(messageCtx.getAxisService());
// if (store == null)
// throw new AxisFault ("Cant find the Savan subscriber store");
// store.store(atomSubscriber);
// }
//
//
// if(!atomFile.exists()){
// throw new AxisFault("no feed exisits for "+feedID.getText() + " no file found "+ atomFile.getAbsolutePath());
// }
// FileInputStream atomIn = new FileInputStream(atomFile);
//add the content of the file to the response
// XMLStreamReader xmlreader = StAXUtils.createXMLStreamReader
// (atomIn, MessageContext.DEFAULT_CHAR_SET_ENCODING);
// StAXBuilder builder = new StAXOMBuilder(fac,xmlreader);
// OMElement result = (OMElement) builder.getDocumentElement();
envelope.getBody().addChild(result);
//send beck the response
MessageContext outMsgContext =
MessageContextBuilder.createOutMessageContext(messageCtx);
outMsgContext.getOperationContext().addMessageContext(outMsgContext);
outMsgContext.setEnvelope(envelope);
AxisEngine.send(outMsgContext);
} else if (HTTPConstants.HEADER_POST.equals(request.getMethod())) {
SOAPEnvelope envlope = messageCtx.getEnvelope();
OMElement bodyContent = envlope.getBody().getFirstElement();
OMElement feedID = bodyContent.getFirstElement();
String pathWRTRepository = "atom/" + feedID.getText();
//remove the file
File atomFile = messageCtx.getConfigurationContext().getRealPath(pathWRTRepository);
atomFile.delete();
//remove the feed from subscriber store
String feedIDAsUrn = feedID.getText().replaceAll("_", ":");
SubscriberStore store = CommonUtil.getSubscriberStore(messageCtx.getAxisService());
if (store == null)
throw new AxisFault("Cant find the Savan subscriber store");
store.delete(feedIDAsUrn);
}
} catch (SOAPProcessingException e) {
e.printStackTrace();
throw AxisFault.makeFault(e);
} catch (OMException e) {
e.printStackTrace();
throw AxisFault.makeFault(e);
// } catch (FileNotFoundException e) {
// e.printStackTrace();
// throw new AxisFault(e);
// } catch (XMLStreamException e) {
// e.printStackTrace();
// throw new AxisFault(e);
// } catch (URISyntaxException e) {
// e.printStackTrace();
// throw new AxisFault(e);
}
}
public SOAPFactory getSOAPFactory(MessageContext msgContext) throws AxisFault {
String nsURI = msgContext.getEnvelope().getNamespace().getNamespaceURI();
if (SOAP12Constants.SOAP_ENVELOPE_NAMESPACE_URI.equals(nsURI)) {
return OMAbstractFactory.getSOAP12Factory();
} else if (SOAP11Constants.SOAP_ENVELOPE_NAMESPACE_URI.equals(nsURI)) {
return OMAbstractFactory.getSOAP11Factory();
} else {
throw new AxisFault(Messages.getMessage("invalidSOAPversion"));
}
}
}
| 6,318 |
0 | Create_ds/axis-axis2-java-savan/modules/core/src/main/java/org/apache/savan | Create_ds/axis-axis2-java-savan/modules/core/src/main/java/org/apache/savan/atom/AtomMessageReceiverDelegator.java | /*
* Copyright 1999-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.savan.atom;
import com.wso2.eventing.atom.CreateFeedResponseDocument;
import com.wso2.eventing.atom.CreateFeedResponseDocument.CreateFeedResponse;
import com.wso2.eventing.atom.RenewFeedResponseDocument;
import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMException;
import org.apache.axiom.om.OMNamespace;
import org.apache.axiom.soap.SOAPEnvelope;
import org.apache.axiom.soap.SOAPFactory;
import org.apache.axiom.soap.SOAPProcessingException;
import org.apache.axis2.AxisFault;
import org.apache.axis2.context.MessageContext;
import org.apache.axis2.databinding.utils.ConverterUtil;
import org.apache.savan.SavanConstants;
import org.apache.savan.SavanException;
import org.apache.savan.SavanMessageContext;
import org.apache.savan.messagereceiver.MessageReceiverDelegator;
import org.apache.savan.storage.SubscriberStore;
import org.apache.savan.subscribers.Subscriber;
import org.apache.savan.util.CommonUtil;
import org.apache.xmlbeans.XmlCursor;
import org.apache.xmlbeans.XmlObject;
import org.w3.x2005.x08.addressing.EndpointReferenceType;
import javax.xml.namespace.QName;
import java.util.Calendar;
import java.util.Date;
public class AtomMessageReceiverDelegator extends MessageReceiverDelegator {
private SOAPEnvelope findOrCreateSoapEnvelope(SavanMessageContext subscriptionMessage,
MessageContext outMessage) throws AxisFault {
MessageContext subscriptionMsgCtx = subscriptionMessage.getMessageContext();
SOAPEnvelope outMessageEnvelope = outMessage.getEnvelope();
SOAPFactory factory = null;
if (outMessageEnvelope != null) {
factory = (SOAPFactory)outMessageEnvelope.getOMFactory();
} else {
factory = (SOAPFactory)subscriptionMsgCtx.getEnvelope().getOMFactory();
outMessageEnvelope = factory.getDefaultEnvelope();
outMessage.setEnvelope(outMessageEnvelope);
}
return outMessageEnvelope;
}
public void handleSubscriptionRequest(SavanMessageContext subscriptionMessage,
MessageContext outMessage) throws SavanException {
try {
if (outMessage != null) {
MessageContext subscriptionMsgCtx = subscriptionMessage.getMessageContext();
SOAPEnvelope outMessageEnvelope =
findOrCreateSoapEnvelope(subscriptionMessage, outMessage);
//setting the action
outMessage.getOptions().setAction(AtomConstants.Actions.SubscribeResponse);
CreateFeedResponseDocument createFeedResponseDocument =
CreateFeedResponseDocument.Factory.newInstance();
CreateFeedResponse createFeedResponse =
createFeedResponseDocument.addNewCreateFeedResponse();
EndpointReferenceType savenEpr = createFeedResponse.addNewSubscriptionManager();
savenEpr.addNewAddress()
.setStringValue(subscriptionMsgCtx.getOptions().getTo().getAddress());
String id = (String)subscriptionMessage
.getProperty(AtomConstants.TransferedProperties.SUBSCRIBER_UUID);
if (id != null) {
XmlCursor c = savenEpr.addNewReferenceParameters().newCursor();
c.toNextToken();
addNameValuePair(c, new QName(AtomConstants.ATOM_NAMESPACE,
AtomConstants.ElementNames.Identifier), id);
} else {
throw new SavanException("Subscription UUID is not set");
}
// HttpServletRequest request = (HttpServletRequest) subscriptionMessage.getProperty(HTTPConstants.MC_HTTP_SERVLETREQUEST);
// request.getServerPort()
createFeedResponse.setFeedUrl(
(String)subscriptionMessage.getProperty(AtomConstants.Properties.feedUrl));
outMessageEnvelope.getBody().addChild(CommonUtil.toOM(createFeedResponseDocument));
} else {
throw new SavanException(
"Eventing protocol need to sent the SubscriptionResponseMessage. But the outMessage is null");
}
//setting the message type
outMessage.setProperty(SavanConstants.MESSAGE_TYPE, new Integer(
SavanConstants.MessageTypes.SUBSCRIPTION_RESPONSE_MESSAGE));
} catch (SOAPProcessingException e) {
throw new SavanException(e);
} catch (AxisFault e) {
throw new SavanException(e);
} catch (OMException e) {
throw new SavanException(e);
}
}
public void handleRenewRequest(SavanMessageContext renewMessage, MessageContext outMessage)
throws SavanException {
try {
if (outMessage == null)
throw new SavanException(
"Eventing protocol need to sent the SubscriptionResponseMessage. But the outMessage is null");
SOAPEnvelope outMessageEnvelope = findOrCreateSoapEnvelope(renewMessage, outMessage);
RenewFeedResponseDocument renewFeedResponseDocument =
RenewFeedResponseDocument.Factory.newInstance();
//setting the action
outMessage.getOptions().setAction(AtomConstants.Actions.RenewResponse);
String subscriberID = (String)renewMessage
.getProperty(AtomConstants.TransferedProperties.SUBSCRIBER_UUID);
if (subscriberID == null) {
String message = "SubscriberID TransferedProperty is not set";
throw new SavanException(message);
}
SubscriberStore store = CommonUtil
.getSubscriberStore(renewMessage.getMessageContext().getAxisService());
Subscriber subscriber = store.retrieve(subscriberID);
AtomSubscriber atomSubscriber = (AtomSubscriber)subscriber;
if (atomSubscriber == null) {
String message = "Cannot find the AbstractSubscriber with the given ID";
throw new SavanException(message);
}
Date expiration = atomSubscriber.getSubscriptionEndingTime();
Calendar calendar = Calendar.getInstance();
calendar.setTime(expiration);
renewFeedResponseDocument.addNewRenewFeedResponse().setExpires(calendar);
outMessageEnvelope.getBody().addChild(CommonUtil.toOM(renewFeedResponseDocument));
//setting the message type
outMessage.setProperty(SavanConstants.MESSAGE_TYPE,
new Integer(SavanConstants.MessageTypes.RENEW_RESPONSE_MESSAGE));
} catch (AxisFault e) {
throw new SavanException(e);
}
}
public void handleEndSubscriptionRequest(SavanMessageContext renewMessage,
MessageContext outMessage) throws SavanException {
try {
if (outMessage == null)
throw new SavanException(
"Eventing protocol need to sent the SubscriptionResponseMessage. But the outMessage is null");
//setting the action
outMessage.getOptions().setAction(AtomConstants.Actions.UnsubscribeResponse);
SOAPEnvelope outMessageEnvelope = findOrCreateSoapEnvelope(renewMessage, outMessage);
outMessageEnvelope.getBody().addChild(OMAbstractFactory.getOMFactory().createOMElement(
new QName(AtomConstants.ATOM_MSG_NAMESPACE,
AtomConstants.ElementNames.deleteFeedResponse)));
outMessage.setProperty(SavanConstants.MESSAGE_TYPE, new Integer(
SavanConstants.MessageTypes.UNSUBSCRIPTION_RESPONSE_MESSAGE));
} catch (AxisFault e) {
throw new SavanException(e);
} catch (OMException e) {
throw new SavanException(e);
}
}
public void handleGetStatusRequest(SavanMessageContext getStatusMessage,
MessageContext outMessage) throws SavanException {
if (outMessage == null)
throw new SavanException(
"Eventing protocol need to sent the SubscriptionResponseMessage. But the outMessage is null");
MessageContext subscriptionMsgCtx = getStatusMessage.getMessageContext();
String id = (String)getStatusMessage
.getProperty(AtomConstants.TransferedProperties.SUBSCRIBER_UUID);
if (id == null)
throw new SavanException("Cannot fulfil request. AbstractSubscriber ID not found");
//setting the action
outMessage.getOptions().setAction(AtomConstants.Actions.UnsubscribeResponse);
SOAPEnvelope outMessageEnvelope = outMessage.getEnvelope();
SOAPFactory factory = null;
if (outMessageEnvelope != null) {
factory = (SOAPFactory)outMessageEnvelope.getOMFactory();
} else {
factory = (SOAPFactory)subscriptionMsgCtx.getEnvelope().getOMFactory();
outMessageEnvelope = factory.getDefaultEnvelope();
try {
outMessage.setEnvelope(outMessageEnvelope);
} catch (AxisFault e) {
throw new SavanException(e);
}
}
SubscriberStore store = CommonUtil
.getSubscriberStore(getStatusMessage.getMessageContext().getAxisService());
if (store == null) {
throw new SavanException("AbstractSubscriber Store was not found");
}
AtomSubscriber subscriber = (AtomSubscriber)store.retrieve(id);
if (subscriber == null) {
throw new SavanException("AbstractSubscriber not found");
}
OMNamespace ens =
factory.createOMNamespace(AtomConstants.ATOM_NAMESPACE, AtomConstants.ATOM_PREFIX);
OMElement getStatusResponseElement =
factory.createOMElement(AtomConstants.ElementNames.GetStatusResponse, ens);
Date expires = subscriber.getSubscriptionEndingTime();
if (expires != null) {
OMElement expiresElement =
factory.createOMElement(AtomConstants.ElementNames.Expires, ens);
Calendar calendar = Calendar.getInstance();
calendar.setTime(expires);
String expirationString = ConverterUtil.convertToString(calendar);
expiresElement.setText(expirationString);
getStatusResponseElement.addChild(expiresElement);
}
outMessageEnvelope.getBody().addChild(getStatusResponseElement);
//setting the message type
outMessage.setProperty(SavanConstants.MESSAGE_TYPE, new Integer(
SavanConstants.MessageTypes.GET_STATUS_RESPONSE_MESSAGE));
}
public static void addNameValuePair(XmlCursor c, QName name, Object value) {
c.beginElement(name);
if (value instanceof String) {
c.insertChars((String)value);
} else {
//Make sure this works, code is taken from
//http://xmlbeans.apache.org/docs/2.0.0/guide/conHandlingAny.html
XmlCursor cc = ((XmlObject)value).newCursor();
cc.toFirstContentToken();
cc.copyXml(c);
cc.dispose();
}
c.toParent();
}
public void doProtocolSpecificProcessing(SavanMessageContext inSavanMessage,
MessageContext outMessage) throws SavanException {
int msgtype = ((Integer)inSavanMessage.getProperty(SavanConstants.MESSAGE_TYPE)).intValue();
switch (msgtype) {
case SavanConstants.MessageTypes.SUBSCRIPTION_MESSAGE:
handleSubscriptionRequest(inSavanMessage, outMessage);
break;
case SavanConstants.MessageTypes.RENEW_MESSAGE:
handleRenewRequest(inSavanMessage, outMessage);
break;
case SavanConstants.MessageTypes.UNSUBSCRIPTION_MESSAGE:
handleEndSubscriptionRequest(inSavanMessage, outMessage);
break;
default:
throw new SavanException("Unknow Message type [" + msgtype + "]");
}
}
public void doProtocolSpecificProcessing(SavanMessageContext inSavanMessage)
throws SavanException {
// TODO Auto-generated method stub
}
}
| 6,319 |
0 | Create_ds/axis-axis2-java-savan/modules/core/src/main/java/org/apache/savan | Create_ds/axis-axis2-java-savan/modules/core/src/main/java/org/apache/savan/atom/AtomSubscriber.java | package org.apache.savan.atom;
import org.apache.axiom.om.OMElement;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.savan.SavanException;
import org.apache.savan.filters.Filter;
import org.apache.savan.subscribers.Subscriber;
import org.apache.savan.subscription.ExpirationBean;
import org.w3.x2005.x08.addressing.EndpointReferenceType;
import java.io.File;
import java.net.URI;
import java.util.Date;
public class AtomSubscriber implements Subscriber {
private static final Log log = LogFactory.getLog(AtomSubscriber.class);
private Date subscriptionEndingTime = null;
//private Feed feed;
private Filter filter = null;
private File atomFile;
private String feedUrl;
private AtomDataSource atomDataSource;
private URI id;
public void init(AtomDataSource dataSource, URI id, String title, String author)
throws SavanException {
this.atomDataSource = dataSource;
atomDataSource.addFeed(id.toString(), title, new Date(), author);
}
public URI getId() {
return id;
}
public void renewSubscription(ExpirationBean bean) {
throw new UnsupportedOperationException();
}
public void sendEventData(OMElement eventData) throws SavanException {
// try {
Date date = new Date();
boolean expired = false;
if (subscriptionEndingTime != null && date.after(subscriptionEndingTime))
expired = true;
if (expired) {
String message = "Cant notify the listener since the subscription has been expired";
log.debug(message);
}
atomDataSource.addEntry(id.toString(), eventData);
//
// if(feed == null){
// feed = new Feed(title,id.toString(),author);
// }
// feed.addEntry(eventData);
//
// if(!atomFile.getParentFile().exists()){
// atomFile.getParentFile().mkdir();
// }
// FileOutputStream out = new FileOutputStream(atomFile);
// feed.write(out);
// out.close();
// System.out.println("Atom file at "+ atomFile + " is updated");
// } catch (FileNotFoundException e) {
// throw new SavanException(e);
// } catch (XMLStreamException e) {
// throw new SavanException(e);
// } catch (IOException e) {
// throw new SavanException(e);
// }
}
public void setId(URI id) {
this.id = id;
}
public void setSubscriptionEndingTime(Date subscriptionEndingTime) {
this.subscriptionEndingTime = subscriptionEndingTime;
}
public void setEndToEPr(EndpointReferenceType endToEPR) {
throw new UnsupportedOperationException();
}
// public String getAuthor() {
// return author;
// }
//
// public void setAuthor(String author) {
// this.author = author;
// }
//
//
// public String getTitle() {
// return title;
// }
// public void setTitle(String title) {
// this.title = title;
// }
public String getFeedUrl() {
return feedUrl;
}
public Date getSubscriptionEndingTime() {
return subscriptionEndingTime;
}
public Filter getFilter() {
return filter;
}
public void setFilter(Filter filter) {
this.filter = filter;
}
public void setAtomFile(File atomFile) {
this.atomFile = atomFile;
}
public void setFeedUrl(String feedUrl) {
this.feedUrl = feedUrl;
}
// public Feed getFeed() {
// return feed;
// }
public OMElement getFeedAsXml() throws SavanException {
return atomDataSource.getFeedAsXml(id.toString());
}
// public void setAtomDataSource(AtomDataSource atomDataSource) {
// this.atomDataSource = atomDataSource;
// }
}
| 6,320 |
0 | Create_ds/axis-axis2-java-savan/modules/core/src/main/java/org/apache/savan | Create_ds/axis-axis2-java-savan/modules/core/src/main/java/org/apache/savan/atom/AtomSubscriptionProcessor.java | /*
* Copyright 1999-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.savan.atom;
import com.wso2.eventing.atom.CreateFeedDocument;
import com.wso2.eventing.atom.CreateFeedDocument.CreateFeed;
import com.wso2.eventing.atom.RenewFeedDocument;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMException;
import org.apache.axiom.om.util.UUIDGenerator;
import org.apache.axiom.soap.SOAPBody;
import org.apache.axiom.soap.SOAPEnvelope;
import org.apache.axiom.soap.SOAPHeader;
import org.apache.axis2.AxisFault;
import org.apache.axis2.context.ServiceContext;
import org.apache.savan.SavanConstants;
import org.apache.savan.SavanException;
import org.apache.savan.SavanMessageContext;
import org.apache.savan.configuration.ConfigurationManager;
import org.apache.savan.configuration.Protocol;
import org.apache.savan.filters.Filter;
import org.apache.savan.filters.XPathBasedFilter;
import org.apache.savan.subscribers.Subscriber;
import org.apache.savan.subscription.ExpirationBean;
import org.apache.savan.subscription.SubscriptionProcessor;
import org.apache.xmlbeans.XmlException;
import javax.xml.namespace.QName;
import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;
public class AtomSubscriptionProcessor extends SubscriptionProcessor {
public void init(SavanMessageContext smc) throws SavanException {
//setting the subscriber_id as a property if possible.
String id = getSubscriberID(smc);
if (id != null) {
smc.setProperty(AtomConstants.TransferedProperties.SUBSCRIBER_UUID, id);
}
// AtomSubscriber atomSubscriber = new AtomSubscriber();
// smc.setProperty(AtomConstants.TransferedProperties.SUBSCRIBER_UUID,id);
// atomSubscriber.setId(new URI(id));
// String atomFeedPath = id.replaceAll(":", "_")+ ".atom";
// atomSubscriber.setAtomFile(new File(realAtomPath,atomFeedPath));
// atomSubscriber.setAuthor("DefaultUser");
// atomSubscriber.setTitle("default Feed");
}
/**
* Sample subscription <createFeed xmlns="http://wso2.com/eventing/atom">
* <EndTo>endpoint-reference</EndTo> ? <Delivery Mode="xs:anyURI"? >xs:any</Delivery>
* <Expires>[xs:dateTime | xs:duration]</Expires> ? <Filter Dialect="xs:anyURI"? > xs:any </Filter>
* ? </createFeed>
*/
public Subscriber getSubscriberFromMessage(SavanMessageContext smc) throws SavanException {
try {
ConfigurationManager configurationManager = (ConfigurationManager)smc
.getConfigurationContext().getProperty(SavanConstants.CONFIGURATION_MANAGER);
if (configurationManager == null)
throw new SavanException("Configuration Manager not set");
Protocol protocol = smc.getProtocol();
if (protocol == null)
throw new SavanException("Protocol not found");
SOAPEnvelope envelope = smc.getEnvelope();
if (envelope == null)
return null;
ServiceContext serviceContext = smc.getMessageContext().getServiceContext();
AtomDataSource dataSource =
(AtomDataSource)serviceContext.getProperty(AtomConstants.Properties.DataSource);
if (dataSource == null) {
dataSource = new AtomDataSource();
serviceContext.setProperty(AtomConstants.Properties.DataSource, dataSource);
}
String subscriberName = protocol.getDefaultSubscriber();
Subscriber subscriber = configurationManager.getSubscriberInstance(subscriberName);
if (!(subscriber instanceof AtomSubscriber)) {
String message =
"Savan only support implementations of Atom subscriber as Subscribers";
throw new SavanException(message);
}
//find the real path for atom feeds
File repositoryPath = smc.getConfigurationContext().getRealPath("/");
File realAtomPath = new File(repositoryPath.getAbsoluteFile(), "atom");
//Get the service URL from request
String serviceAddress = smc.getMessageContext().getTo().getAddress();
int cutIndex = serviceAddress.indexOf("services");
if (cutIndex > 0) {
serviceAddress = serviceAddress.substring(0, cutIndex - 1);
}
AtomSubscriber atomSubscriber = (AtomSubscriber)subscriber;
String id = UUIDGenerator.getUUID();
smc.setProperty(AtomConstants.TransferedProperties.SUBSCRIBER_UUID, id);
atomSubscriber.setId(new URI(id));
String atomFeedPath = id2Path(id);
atomSubscriber.setAtomFile(new File(realAtomPath, atomFeedPath));
atomSubscriber.setFeedUrl(serviceAddress + "/services/" + smc.getMessageContext()
.getServiceContext().getAxisService().getName() + "/atom?feed=" + atomFeedPath);
SOAPBody body = envelope.getBody();
CreateFeedDocument createFeedDocument =
CreateFeedDocument.Factory.parse(body.getFirstElement().getXMLStreamReader());
CreateFeed createFeed = createFeedDocument.getCreateFeed();
if (createFeed.getEndTo() != null) {
atomSubscriber.setEndToEPr(createFeed.getEndTo());
}
if (createFeed.getExpires() != null) {
atomSubscriber.setSubscriptionEndingTime(createFeed.getExpires().getTime());
}
if (createFeed.getFilter() != null) {
Filter filter = null;
String filterKey = createFeed.getFilter().getDialect();
filter = configurationManager.getFilterInstanceFromId(filterKey);
if (filter == null)
throw new SavanException("The Filter defined by the dialect is not available");
if (filter instanceof XPathBasedFilter) {
((XPathBasedFilter)filter)
.setXPathString(createFeed.getFilter().getStringValue());
} else {
throw new SavanException("Only Xpath fileters are supported");
}
atomSubscriber.setFilter(filter);
}
atomSubscriber
.init(dataSource, new URI(id), createFeed.getTitle(), createFeed.getAuthor());
smc.setProperty(AtomConstants.Properties.feedUrl, atomSubscriber.getFeedUrl());
return atomSubscriber;
} catch (AxisFault e) {
throw new SavanException(e);
} catch (OMException e) {
throw new SavanException(e);
} catch (XmlException e) {
throw new SavanException(e);
} catch (URISyntaxException e) {
throw new SavanException(e);
}
}
// private String findValue(String localName,OMElement parent,boolean throwfault) throws SavanException{
// return findValue(AtomConstants.ATOM_NAMESPACE, localName, parent, throwfault);
// }
private String findValue(String nsURI, String localName, OMElement parent, boolean throwfault)
throws SavanException {
QName name = new QName(nsURI, AtomConstants.IDEDNTIFIER_ELEMENT);
OMElement ele = parent.getFirstChildWithName(name);
if (ele != null) {
return ele.getText();
} else {
if (throwfault) {
throw new SavanException(localName + " element is not defined");
} else {
return null;
}
}
}
// private OMElement findElement(String localName,OMElement parent,boolean throwfault) throws SavanException{
// QName name = new QName (AtomConstants.ATOM_NAMESPACE,AtomConstants.ID_ELEMENT);
// OMElement ele = parent.getFirstChildWithName(name);
// if(ele != null){
// return ele;
// }else{
// if(throwfault){
// throw new SavanException (localName + " element is not defined");
// }else{
// return null;
// }
// }
// }
public void pauseSubscription(SavanMessageContext pauseSubscriptionMessage)
throws SavanException {
throw new UnsupportedOperationException(
"Eventing specification does not support this type of messages");
}
public void resumeSubscription(SavanMessageContext resumeSubscriptionMessage)
throws SavanException {
throw new UnsupportedOperationException(
"Eventing specification does not support this type of messages");
}
/** <renewFeed><Expires></Expires></renewFeed> */
public ExpirationBean getExpirationBean(SavanMessageContext renewMessage)
throws SavanException {
try {
SOAPEnvelope envelope = renewMessage.getEnvelope();
RenewFeedDocument renewFeedDocument =
RenewFeedDocument.Factory.parse(envelope.getBody().getXMLStreamReader());
// SOAPBody body = envelope.getBody();
//
ExpirationBean expirationBean = new ExpirationBean();
// OMElement renewFeedEle = findElement(AtomConstants.RENEW_FEED, body, true);
// Date expieringTime = getExpirationBeanFromString(findValue(AtomConstants.EXPIRES_ELEMENT, renewFeedEle, true));
expirationBean.setDuration(false);
expirationBean.setDateValue(renewFeedDocument.getRenewFeed().getExpires().getTime());
String subscriberID = getSubscriberID(renewMessage);
if (subscriberID == null) {
String message = "Cannot find the subscriber ID";
throw new SavanException(message);
}
renewMessage
.setProperty(AtomConstants.TransferedProperties.SUBSCRIBER_UUID, subscriberID);
expirationBean.setSubscriberID(subscriberID);
return expirationBean;
} catch (OMException e) {
throw new SavanException(e);
} catch (XmlException e) {
throw new SavanException(e);
}
}
public String getSubscriberID(SavanMessageContext smc) throws SavanException {
SOAPEnvelope envelope = smc.getEnvelope();
SOAPHeader header = envelope.getHeader();
if (header == null) {
return null;
}
return findValue(AtomConstants.ATOM_NAMESPACE, AtomConstants.IDEDNTIFIER_ELEMENT,
envelope.getHeader(), false);
}
public void unsubscribe(SavanMessageContext endSubscriptionMessage) throws SavanException {
String subscriberID = getSubscriberID(endSubscriptionMessage);
File feedPath = endSubscriptionMessage.getConfigurationContext()
.getRealPath("atom/" + id2Path(subscriberID));
if (feedPath.exists()) {
feedPath.delete();
}
super.unsubscribe(endSubscriptionMessage);
}
private String id2Path(String id) {
return id.replaceAll(":", "_") + ".atom";
}
}
| 6,321 |
0 | Create_ds/axis-axis2-java-savan/modules/core/src/main/java/org/apache/savan | Create_ds/axis-axis2-java-savan/modules/core/src/main/java/org/apache/savan/atom/AtomEventingClient.java | package org.apache.savan.atom;
import com.wso2.eventing.atom.CreateFeedDocument;
import com.wso2.eventing.atom.CreateFeedDocument.CreateFeed;
import com.wso2.eventing.atom.CreateFeedResponseDocument;
import com.wso2.eventing.atom.CreateFeedResponseDocument.CreateFeedResponse;
import com.wso2.eventing.atom.FilterType;
import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.impl.builder.StAXOMBuilder;
import org.apache.axis2.AxisFault;
import org.apache.axis2.addressing.AddressingConstants;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.client.Options;
import org.apache.axis2.client.ServiceClient;
import org.apache.axis2.context.ConfigurationContext;
import org.apache.axis2.context.ConfigurationContextFactory;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.savan.SavanException;
import org.apache.savan.eventing.EventingConstants;
import org.apache.savan.filters.XPathBasedFilter;
import org.apache.savan.util.CommonUtil;
import org.apache.xmlbeans.XmlException;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLStreamException;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Calendar;
import java.util.Iterator;
/**
* This class take provide client interface for Savan atom support
*
* @author Srinath Perera(hemapani@apache.org)
*/
public class AtomEventingClient {
private ServiceClient serviceClient = null;
private EndpointReference feedEpr;
public AtomEventingClient(String serviceUrl, String clientRepository) throws AxisFault {
ConfigurationContext configContext = ConfigurationContextFactory
.createConfigurationContextFromFileSystem(clientRepository,
clientRepository + "/conf/axis2.xml");
serviceClient = new ServiceClient(configContext, null); //TODO give a repo
Options options = new Options();
serviceClient.setOptions(options);
serviceClient.engageModule(new QName("addressing"));
options.setTo(new EndpointReference(serviceUrl));
}
public AtomEventingClient(ServiceClient serviceClient) {
this.serviceClient = serviceClient;
}
public CreateFeedResponse createFeed(String title, String author)
throws AxisFault {
return createFeed(title, author, null, null);
}
public CreateFeedResponse createFeed(String title, String author,
Calendar expiredTime, String xpathFilter)
throws AxisFault {
try {
serviceClient.getOptions().setAction(
AtomConstants.Actions.Subscribe);
CreateFeedDocument createFeedDocument = CreateFeedDocument.Factory
.newInstance();
CreateFeed createFeed = createFeedDocument.addNewCreateFeed();
createFeed.setAuthor(author);
createFeed.setTitle(title);
if (expiredTime != null) {
createFeed.setExpires(expiredTime);
}
if (xpathFilter != null) {
FilterType filter = createFeed.addNewFilter();
filter.setDialect(XPathBasedFilter.XPATH_BASED_FILTER);
filter.setStringValue(xpathFilter);
}
OMElement request = CommonUtil.toOM(createFeedDocument);
request.build();
OMElement element = serviceClient.sendReceive(request);
CreateFeedResponseDocument createFeedResponseDocument =
CreateFeedResponseDocument.Factory
.parse(element.getXMLStreamReader());
System.out.println(createFeedDocument.xmlText());
// read epr for subscription from response and store it
OMElement responseAsOM = CommonUtil
.toOM(createFeedResponseDocument);
OMElement eprAsOM = responseAsOM.getFirstChildWithName(new QName(
AtomConstants.ATOM_MSG_NAMESPACE, "SubscriptionManager"));
feedEpr = new EndpointReference(eprAsOM.getFirstElement().getText());
OMElement referanceParameters = eprAsOM
.getFirstChildWithName(new QName(eprAsOM.getFirstElement()
.getNamespace().getNamespaceURI(),
AddressingConstants.EPR_REFERENCE_PARAMETERS));
Iterator refparams = referanceParameters.getChildElements();
while (refparams.hasNext()) {
feedEpr.addReferenceParameter((OMElement)refparams.next());
}
return createFeedResponseDocument.getCreateFeedResponse();
} catch (XmlException e) {
throw AxisFault.makeFault(e);
}
}
public void deleteFeed(EndpointReference epr) throws AxisFault {
serviceClient.getOptions().setAction(AtomConstants.Actions.Unsubscribe);
serviceClient.getOptions().setTo(epr);
OMElement request = OMAbstractFactory.getOMFactory().createOMElement(
new QName(AtomConstants.ATOM_MSG_NAMESPACE, "DeleteFeed"));
serviceClient.sendReceive(request);
}
public void deleteFeed() throws AxisFault {
if (feedEpr != null) {
deleteFeed(feedEpr);
} else {
throw new AxisFault(
"No feed epr alreday stored, you must have create a feed using same AtomEventingClient Object");
}
}
public OMElement fetchFeed(String url) throws SavanException {
// Create an instance of HttpClient.
HttpClient client = new HttpClient();
// Create a method instance.
GetMethod method = new GetMethod(url);
try {
// Execute the method.
int statusCode = client.executeMethod(method);
if (statusCode != HttpStatus.SC_OK) {
throw new SavanException("Method failed: " + method.getStatusLine());
}
// Read the response body.
byte[] responseBody = method.getResponseBody();
StAXOMBuilder builder = new StAXOMBuilder(new ByteArrayInputStream(
responseBody));
return builder.getDocumentElement();
} catch (IOException e) {
throw new SavanException(e);
} catch (XMLStreamException e) {
throw new SavanException(e);
} finally {
// Release the connection.
method.releaseConnection();
}
}
public void publishWithREST(String serviceurl, final OMElement content, String topic)
throws SavanException {
// Create an instance of HttpClient.
HttpClient client = new HttpClient();
StringBuffer queryUrl = new StringBuffer(serviceurl);
if (!serviceurl.endsWith("/")) {
queryUrl.append("/");
}
queryUrl.append("publish");
if (topic != null) {
queryUrl.append("?").append(EventingConstants.ElementNames.Topic).append("=")
.append(topic);
}
PostMethod method = new PostMethod(queryUrl.toString());
// Request content will be retrieved directly
// from the input stream
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
content.serialize(out);
out.flush();
final byte[] data = out.toByteArray();
RequestEntity entity = new RequestEntity() {
public void writeRequest(OutputStream outstream)
throws IOException {
outstream.write(data);
}
public boolean isRepeatable() {
return false;
}
public String getContentType() {
return "text/xml";
}
public long getContentLength() {
return data.length;
}
};
method.setRequestEntity(entity);
// Execute the method.
int statusCode = client.executeMethod(method);
if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_ACCEPTED) {
throw new SavanException("Method failed: " + method.getStatusLine());
}
} catch (IOException e) {
throw new SavanException(e);
} catch (XMLStreamException e) {
throw new SavanException(e);
} finally {
// Release the connection.
method.releaseConnection();
}
}
public void publishWithSOAP(String serviceurl, final OMElement content, String topic)
throws SavanException {
try {
Options options = serviceClient.getOptions();
EndpointReference to = new EndpointReference(serviceurl);
if (topic != null) {
to.addReferenceParameter(new QName(EventingConstants.EXTENDED_EVENTING_NAMESPACE,
EventingConstants.ElementNames.Topic), topic);
}
options.setAction(EventingConstants.Actions.Publish);
serviceClient.fireAndForget(content);
} catch (AxisFault e) {
throw new SavanException(e);
}
}
}
| 6,322 |
0 | Create_ds/axis-axis2-java-savan/modules/core/src/main/java/org/apache/savan | Create_ds/axis-axis2-java-savan/modules/core/src/main/java/org/apache/savan/atom/AtomUtilFactory.java | /*
* Copyright 1999-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.savan.atom;
import org.apache.axis2.context.MessageContext;
import org.apache.savan.SavanConstants;
import org.apache.savan.SavanMessageContext;
import org.apache.savan.messagereceiver.MessageReceiverDelegator;
import org.apache.savan.subscribers.Subscriber;
import org.apache.savan.subscription.SubscriptionProcessor;
import org.apache.savan.util.UtilFactory;
public class AtomUtilFactory implements UtilFactory {
public AtomUtilFactory() {
}
/** this is a way to map different actions to different types of operations */
public SavanMessageContext initializeMessage(SavanMessageContext smc) {
MessageContext messageContext = smc.getMessageContext();
//setting the message type.
String action = messageContext.getOptions().getAction();
if (AtomConstants.Actions.Subscribe.equals(action))
smc.setMessageType(SavanConstants.MessageTypes.SUBSCRIPTION_MESSAGE);
else if (AtomConstants.Actions.Renew.equals(action))
smc.setMessageType(SavanConstants.MessageTypes.RENEW_MESSAGE);
else if (AtomConstants.Actions.Unsubscribe.equals(action))
smc.setMessageType(SavanConstants.MessageTypes.UNSUBSCRIPTION_MESSAGE);
else if (AtomConstants.Actions.GetStatus.equals(action))
smc.setMessageType(SavanConstants.MessageTypes.GET_STATUS_MESSAGE);
else if (AtomConstants.Actions.SubscribeResponse.equals(action))
smc.setMessageType(SavanConstants.MessageTypes.SUBSCRIPTION_RESPONSE_MESSAGE);
else if (AtomConstants.Actions.RenewResponse.equals(action))
smc.setMessageType(SavanConstants.MessageTypes.RENEW_RESPONSE_MESSAGE);
else if (AtomConstants.Actions.UnsubscribeResponse.equals(action))
smc.setMessageType(SavanConstants.MessageTypes.UNSUBSCRIPTION_RESPONSE_MESSAGE);
else if (AtomConstants.Actions.GetStatusResponse.equals(action))
smc.setMessageType(SavanConstants.MessageTypes.GET_STATUS_RESPONSE_MESSAGE);
else
smc.setMessageType(SavanConstants.MessageTypes.UNKNOWN);
return smc;
}
public SubscriptionProcessor createSubscriptionProcessor() {
return new AtomSubscriptionProcessor();
}
public MessageReceiverDelegator createMessageReceiverDelegator() {
return new AtomMessageReceiverDelegator();
}
public Subscriber createSubscriber() {
return new AtomSubscriber();
}
}
| 6,323 |
0 | Create_ds/axis-axis2-java-savan/modules/core/src/main/java/org/apache/savan | Create_ds/axis-axis2-java-savan/modules/core/src/main/java/org/apache/savan/atom/AtomDataSource.java | package org.apache.savan.atom;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.impl.builder.StAXBuilder;
import org.apache.axiom.om.impl.builder.StAXOMBuilder;
import org.apache.axiom.om.util.StAXUtils;
import org.apache.axis2.context.MessageContext;
import org.apache.savan.SavanException;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringWriter;
import java.sql.*;
import java.util.Date;
import java.util.Properties;
/**
* This class interface between Derby and Savan atom implementation
*
* @author Srinath Perera(hemapani@apache.org)
*/
public class AtomDataSource {
public static final String SQL_CREATE_FEEDS = "CREATE TABLE FEEDS(id CHAR(250) NOT NULL, " +
"title CHAR(250), updated TIMESTAMP, author CHAR(250), PRIMARY KEY(id))";
public static final String SQL_CREATE_ENTRIES =
"CREATE TABLE ENTIES(feed CHAR(250), content VARCHAR(2000))";
public static final String SQL_ADD_FEED =
"INSERT INTO FEEDS(id,title, updated,author) VALUES(?,?,?,?)";
public static final String SQL_ADD_ENTRY = "INSERT INTO ENTIES(feed, content) VALUES(?,?)";
public static final String SQL_GET_ENTRIES_4_FEED = "SELECT content from ENTIES WHERE feed=?";
public static final String SQL_GET_FEED_DATA =
"SELECT id,title,updated,author from FEEDS WHERE id=?";
public String framework = "embedded";
public String driver = "org.apache.derby.jdbc.EmbeddedDriver";
public String protocol = "jdbc:derby:";
private Properties props;
public AtomDataSource() throws SavanException {
try {
Class.forName(driver).newInstance();
System.out.println("Loaded the appropriate driver.");
props = new Properties();
props.put("user", "user1");
props.put("password", "user1");
Connection connection = getConnection();
Statement statement = connection.createStatement();
ResultSet feedtable = connection.getMetaData().getTables(null, null, "FEEDS", null);
if (!feedtable.next()) {
statement.execute(SQL_CREATE_FEEDS);
}
ResultSet entirestable = connection.getMetaData().getTables(null, null, "ENTIES", null);
if (!entirestable.next()) {
statement.execute(SQL_CREATE_ENTRIES);
}
connection.close();
} catch (InstantiationException e) {
throw new SavanException(e);
} catch (IllegalAccessException e) {
throw new SavanException(e);
} catch (ClassNotFoundException e) {
throw new SavanException(e);
} catch (SQLException e) {
throw new SavanException(e);
}
}
public Connection getConnection() throws SavanException {
try {
/*
The connection specifies create=true to cause
the database to be created. To remove the database,
remove the directory derbyDB and its contents.
The directory derbyDB will be created under
the directory that the system property
derby.system.home points to, or the current
directory if derby.system.home is not set.
*/
return DriverManager.getConnection(protocol +
"derbyDB;create=true", props);
} catch (SQLException e) {
throw new SavanException(e);
}
}
public void addFeed(String id, String title, Date lastEditedtime, String author)
throws SavanException {
try {
Connection connection = getConnection();
try {
PreparedStatement statement = connection.prepareStatement(SQL_ADD_FEED);
statement.setString(1, id);
statement.setString(2, title);
Timestamp t = new Timestamp(lastEditedtime.getTime());
statement.setTimestamp(3, t);
statement.setString(4, author);
statement.executeUpdate();
} finally {
connection.close();
}
} catch (SQLException e) {
throw new SavanException(e);
}
}
public void addEntry(String id, OMElement entry) throws SavanException {
try {
StringWriter w = new StringWriter();
entry.serialize(w);
Connection connection = getConnection();
try {
PreparedStatement statement = connection.prepareStatement(SQL_ADD_ENTRY);
statement.setString(1, id);
statement.setString(2, w.getBuffer().toString());
statement.executeUpdate();
} finally {
connection.close();
}
} catch (SQLException e) {
throw new SavanException(e);
} catch (XMLStreamException e) {
throw new SavanException(e);
}
}
public OMElement getFeedAsXml(String feedId) throws SavanException {
try {
Connection connection = getConnection();
try {
PreparedStatement statement = connection.prepareStatement(SQL_GET_FEED_DATA);
statement.setString(1, feedId);
ResultSet results = statement.executeQuery();
if (results.next()) {
String title = results.getString("title");
Timestamp updatedTime = results.getTimestamp("updated");
String author = results.getString("author");
Feed feed = new Feed(title, feedId, author, updatedTime);
statement.close();
statement = connection.prepareStatement(SQL_GET_ENTRIES_4_FEED);
statement.setString(1, feedId);
results = statement.executeQuery();
while (results.next()) {
String entryAsStr = results.getString("content");
InputStream atomIn = new ByteArrayInputStream(entryAsStr.getBytes());
XMLStreamReader xmlreader = StAXUtils.createXMLStreamReader(atomIn,
MessageContext.DEFAULT_CHAR_SET_ENCODING);
StAXBuilder builder = new StAXOMBuilder(feed.getFactory(), xmlreader);
feed.addEntry(builder.getDocumentElement());
}
return feed.getFeedAsXml();
} else {
throw new SavanException("No such feed " + feedId);
}
} finally {
connection.close();
}
} catch (SQLException e) {
throw new SavanException(e);
} catch (XMLStreamException e) {
throw new SavanException(e);
}
}
}
| 6,324 |
0 | Create_ds/axis-axis2-java-savan/modules/core/src/main/java/org/apache/savan | Create_ds/axis-axis2-java-savan/modules/core/src/main/java/org/apache/savan/atom/AtomConstants.java | package org.apache.savan.atom;
/** @author Srinath Perera(hemapani@apache.org) */
public class AtomConstants {
public static String ATOM_NAMESPACE = "http://www.w3.org/2005/Atom";
public static String ATOM_PREFIX = "atom";
public static String ATOM_MSG_NAMESPACE = "http://wso2.com/eventing/atom/";
public static String ENDTO_ELEMENT = "EndTo";
public static String EXPIRES_ELEMENT = "Expires";
public static String FILTER_ELEMENT = "Filter";
public static String TITLE_ELEMENT = "title";
public static String ID_ELEMENT = "id";
public static String AUTHOR_ELEMENT = "author";
public static String DIALECT_ELEMENT = "Dialect";
public static String RENEW_FEED = "renewFeed";
public static String IDEDNTIFIER_ELEMENT = "Identifier";
public static String DEFAULT_FILTER_IDENTIFIER = FilterDialects.XPath;
interface FilterDialects {
String XPath = "http://www.w3.org/TR/1999/REC-xpath-19991116";
}
interface Actions {
String Subscribe = "http://wso2.com/eventing/Subscribe";
String SubscribeResponse = "http://wso2.com/eventing/SubscribeResponse";
String Renew = "http://wso2.com/eventing/Renew";
String RenewResponse = "http://wso2.com/eventing/RenewResponse";
String Unsubscribe = "http://wso2.com/eventing/Unsubscribe";
String UnsubscribeResponse = "http://wso2.com/eventing/UnsubscribeResponse";
String GetStatus = "http://wso2.com/eventing/GetStatus";
String GetStatusResponse = "http://wso2.com/eventing/GetStatusResponse";
}
interface TransferedProperties {
String SUBSCRIBER_UUID = "SAVAN_EVENTING_SUBSCRIBER_UUID";
}
public interface ElementNames {
String Subscribe = "Subscribe";
String EndTo = "EndTo";
String Delivery = "Delivery";
String Mode = "Mode";
String NotifyTo = "NotifyTo";
String Expires = "Expires";
String Filter = "Filter";
String Dialect = "Dialect";
String SubscribeResponse = "SubscribeResponse";
String SubscriptionManager = "SubscriptionManager";
String Renew = "Renew";
String RenewResponse = "RenewResponse";
String Identifier = "Identifier";
String Unsubscribe = "Unsubscribe";
String GetStatus = "GetStatus";
String GetStatusResponse = "GetStatusResponse";
String FeedUrl = "FeedUrl";
String Entry = "entry";
String Content = "content";
String deleteFeedResponse = "DeleteFeedResponse";
}
interface Properties {
String SOAPVersion = "SOAPVersion";
String feedUrl = "feedUrl";
String DataSource = "DataSource";
}
}
| 6,325 |
0 | Create_ds/axis-axis2-java-savan/modules/core/src/main/java/org/apache/savan | Create_ds/axis-axis2-java-savan/modules/core/src/main/java/org/apache/savan/module/SavanModule.java | /*
* Copyright 1999-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.savan.module;
import org.apache.axis2.AxisFault;
import org.apache.axis2.context.ConfigurationContext;
import org.apache.axis2.description.AxisDescription;
import org.apache.axis2.description.AxisModule;
import org.apache.axis2.description.AxisService;
import org.apache.axis2.modules.Module;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.neethi.Assertion;
import org.apache.neethi.Policy;
import org.apache.savan.SavanConstants;
import org.apache.savan.SavanException;
import org.apache.savan.configuration.ConfigurationManager;
/** Savan Module class. */
public class SavanModule implements Module {
private static final Log log = LogFactory.getLog(SavanModule.class);
public void engageNotify(AxisDescription axisDescription) throws AxisFault {
//adding a subscriber store to the description
if (axisDescription instanceof AxisService) { //TODO remove this restriction
//TODO set a suitable SubscriberStore for the service.
}
}
public void init(ConfigurationContext configContext, AxisModule module) throws AxisFault {
ConfigurationManager configurationManager = new ConfigurationManager();
try {
ClassLoader moduleClassLoader = module.getModuleClassLoader();
configurationManager.configure(moduleClassLoader);
} catch (SavanException e) {
log.error("Exception thrown while trying to configure the Savan module", e);
}
configContext.setProperty(SavanConstants.CONFIGURATION_MANAGER, configurationManager);
}
public void shutdown(ConfigurationContext configurationContext) throws AxisFault {
}
public void applyPolicy(Policy policy, AxisDescription axisDescription) throws AxisFault {
// TODO
}
public boolean canSupportAssertion(Assertion assertion) {
// TODO
return true;
}
}
| 6,326 |
0 | Create_ds/axis-axis2-java-savan/modules/core/src/main/java/org/apache/savan | Create_ds/axis-axis2-java-savan/modules/core/src/main/java/org/apache/savan/messagereceiver/SavanInOutMessageReceiver.java | /*
* Copyright 1999-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.savan.messagereceiver;
import org.apache.axis2.AxisFault;
import org.apache.axis2.context.MessageContext;
import org.apache.axis2.receivers.AbstractInOutSyncMessageReceiver;
import org.apache.savan.SavanException;
import org.apache.savan.SavanMessageContext;
import org.apache.savan.configuration.Protocol;
import org.apache.savan.util.ProtocolManager;
import org.apache.savan.util.UtilFactory;
/** InOut message deceiver for Savan. May get called for control messages depending on the protocol. */
public class SavanInOutMessageReceiver extends AbstractInOutSyncMessageReceiver {
public void invokeBusinessLogic(MessageContext inMessage, MessageContext outMessage)
throws AxisFault {
SavanMessageContext savanInMessage = new SavanMessageContext(inMessage);
//setting the Protocol
Protocol protocol = ProtocolManager.getMessageProtocol(savanInMessage);
if (protocol == null) {
//this message does not have a matching protocol
//so let it go
throw new SavanException("Cannot find a matching protocol");
}
savanInMessage.setProtocol(protocol);
UtilFactory utilFactory = protocol.getUtilFactory();
MessageReceiverDelegator delegator = utilFactory.createMessageReceiverDelegator();
delegator.processMessage(savanInMessage);
delegator.doProtocolSpecificProcessing(savanInMessage, outMessage);
}
}
| 6,327 |
0 | Create_ds/axis-axis2-java-savan/modules/core/src/main/java/org/apache/savan | Create_ds/axis-axis2-java-savan/modules/core/src/main/java/org/apache/savan/messagereceiver/MessageReceiverDelegator.java | /*
* Copyright 1999-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.savan.messagereceiver;
import org.apache.axis2.AxisFault;
import org.apache.axis2.context.MessageContext;
import org.apache.axis2.description.AxisService;
import org.apache.axis2.description.Parameter;
import org.apache.savan.SavanConstants;
import org.apache.savan.SavanException;
import org.apache.savan.SavanMessageContext;
import org.apache.savan.configuration.ConfigurationManager;
import org.apache.savan.configuration.Protocol;
import org.apache.savan.storage.SubscriberStore;
import org.apache.savan.subscription.SubscriptionProcessor;
import org.apache.savan.util.UtilFactory;
/** Provide abstract functions that may be done by protocols at the MessageReceiver level. */
public abstract class MessageReceiverDelegator {
public void processMessage(SavanMessageContext smc) throws SavanException {
MessageContext msgContext = smc.getMessageContext();
//setting the Protocol
Protocol protocol = smc.getProtocol();
if (protocol == null) {
//this message does not have a matching protocol
//so let it go
throw new SavanException("Cannot find a matching protocol");
}
smc.setProtocol(protocol);
AxisService axisService = msgContext.getAxisService();
if (axisService == null)
throw new SavanException("Service context is null");
//setting the AbstractSubscriber Store
Parameter parameter = axisService.getParameter(SavanConstants.SUBSCRIBER_STORE);
if (parameter == null) {
setSubscriberStore(smc);
}
UtilFactory utilFactory = smc.getProtocol().getUtilFactory();
utilFactory.initializeMessage(smc);
int messageType = smc.getMessageType();
SubscriptionProcessor processor = utilFactory.createSubscriptionProcessor();
processor.init(smc);
switch (messageType) {
case SavanConstants.MessageTypes.SUBSCRIPTION_MESSAGE:
processor.subscribe(smc);
break;
case SavanConstants.MessageTypes.UNSUBSCRIPTION_MESSAGE:
processor.unsubscribe(smc);
break;
case SavanConstants.MessageTypes.RENEW_MESSAGE:
processor.renewSubscription(smc);
break;
case SavanConstants.MessageTypes.PUBLISH:
processor.publish(smc);
break;
case SavanConstants.MessageTypes.GET_STATUS_MESSAGE:
processor.getStatus(smc);
break;
}
}
private void setSubscriberStore(SavanMessageContext smc) throws SavanException {
MessageContext msgContext = smc.getMessageContext();
AxisService axisService = msgContext.getAxisService();
Parameter parameter = axisService.getParameter(SavanConstants.SUBSCRIBER_STORE_KEY);
String subscriberStoreKey = SavanConstants.DEFAULT_SUBSCRIBER_STORE_KEY;
if (parameter != null)
subscriberStoreKey = (String)parameter.getValue();
ConfigurationManager configurationManager = (ConfigurationManager)smc
.getConfigurationContext().getProperty(SavanConstants.CONFIGURATION_MANAGER);
SubscriberStore store = configurationManager.getSubscriberStoreInstance(subscriberStoreKey);
parameter = new Parameter();
parameter.setName(SavanConstants.SUBSCRIBER_STORE);
parameter.setValue(store);
try {
axisService.addParameter(parameter);
} catch (AxisFault e) {
throw new SavanException(e);
}
}
public abstract void doProtocolSpecificProcessing(SavanMessageContext inSavanMessage,
MessageContext outMessage)
throws SavanException;
public abstract void doProtocolSpecificProcessing(SavanMessageContext inSavanMessage)
throws SavanException;
}
| 6,328 |
0 | Create_ds/axis-axis2-java-savan/modules/core/src/main/java/org/apache/savan | Create_ds/axis-axis2-java-savan/modules/core/src/main/java/org/apache/savan/messagereceiver/PublishingMessageReceiver.java | package org.apache.savan.messagereceiver;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMException;
import org.apache.axiom.soap.SOAPEnvelope;
import org.apache.axis2.AxisFault;
import org.apache.axis2.context.MessageContext;
import org.apache.axis2.context.ServiceContext;
import org.apache.axis2.engine.MessageReceiver;
import org.apache.savan.atom.AtomConstants;
import org.apache.savan.eventing.EventingConstants;
import org.apache.savan.publication.client.PublicationClient;
import javax.xml.namespace.QName;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.StringTokenizer;
/**
* This Message reciver handles the publish requests. It will received all messages sent to SOAP/WS
* action http://ws.apache.org/ws/2007/05/eventing-extended/Publish, or request URL
* http://<host>:port//services/<service-name>/publish. It will search for topic in URL query
* parameter "topic" or Soap Header <eevt::topic xmlns="http://ws.apache.org/ws/2007/05/eventing-extended">...</topic>
*
* @author Srinath Perera (hemapani@apache.org)
*/
public class PublishingMessageReceiver implements MessageReceiver {
public void receive(MessageContext messageCtx) throws AxisFault {
try {
String toAddress = messageCtx.getTo().getAddress();
//Here we try to locate the topic. It can be either a query parameter of the input address or a header
//in the SOAP evvelope
URI topic = null;
SOAPEnvelope requestEnvelope = messageCtx.getEnvelope();
int querySeperatorIndex = toAddress.indexOf('?');
if (querySeperatorIndex > 0) {
String queryString = toAddress.substring(querySeperatorIndex + 1);
HashMap map = new HashMap();
StringTokenizer t = new StringTokenizer(queryString, "=&");
while (t.hasMoreTokens()) {
map.put(t.nextToken(), t.nextToken());
}
if (map.containsKey(EventingConstants.ElementNames.Topic)) {
topic = new URI((String)map.get(EventingConstants.ElementNames.Topic));
}
} else {
OMElement topicHeader = requestEnvelope.getHeader().getFirstChildWithName(
new QName(EventingConstants.EXTENDED_EVENTING_NAMESPACE,
EventingConstants.ElementNames.Topic));
if (topicHeader != null) {
topic = new URI(topicHeader.getText());
}
}
//Here we locate the content of the Event. If this is APP we unwrap APP wrapping elements.
OMElement eventData = requestEnvelope.getBody().getFirstElement();
if (AtomConstants.ATOM_NAMESPACE.equals(eventData.getNamespace().getNamespaceURI()) &&
AtomConstants.ElementNames.Entry.equals(eventData.getLocalName())) {
OMElement content = eventData.getFirstChildWithName(new QName(
AtomConstants.ATOM_NAMESPACE, AtomConstants.ElementNames.Content));
if (content != null && content.getFirstElement() != null) {
eventData.getFirstElement();
}
}
//Use in memory API to publish the event
ServiceContext serviceContext = messageCtx.getServiceContext();
PublicationClient client =
new PublicationClient(serviceContext.getConfigurationContext());
client.sendPublication(eventData, serviceContext.getAxisService(), topic);
} catch (OMException e) {
throw AxisFault.makeFault(e);
} catch (URISyntaxException e) {
throw AxisFault.makeFault(e);
}
}
}
| 6,329 |
0 | Create_ds/axis-axis2-java-savan/modules/core/src/main/java/org/apache/savan | Create_ds/axis-axis2-java-savan/modules/core/src/main/java/org/apache/savan/messagereceiver/SavanInOnlyMessageReceiver.java | /*
* Copyright 1999-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.savan.messagereceiver;
import org.apache.axis2.AxisFault;
import org.apache.axis2.context.MessageContext;
import org.apache.axis2.receivers.AbstractInMessageReceiver;
/**
* InOnly message deceiver for Savan. May get called for control messages depending on the
* protocol.
*/
public class SavanInOnlyMessageReceiver extends AbstractInMessageReceiver {
public void invokeBusinessLogic(MessageContext inMessage) throws AxisFault {
}
}
| 6,330 |
0 | Create_ds/axis-axis2-java-savan/modules/core/src/main/java/org/apache/savan | Create_ds/axis-axis2-java-savan/modules/core/src/main/java/org/apache/savan/storage/SubscriberStore.java | /*
* Copyright 2004,2005 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.savan.storage;
import org.apache.axis2.context.ConfigurationContext;
import org.apache.savan.SavanException;
import org.apache.savan.subscribers.Subscriber;
import org.apache.savan.subscribers.SubscriberGroup;
import java.util.Iterator;
/** Defines the Storage for storing subscribers. */
public interface SubscriberStore {
/**
* To Initialize the storage.
*
* @param configurationContext
* @throws SavanException
*/
void init(ConfigurationContext configurationContext) throws SavanException;
/**
* To store the subscriber.
*
* @param s
* @throws SavanException
*/
void store(Subscriber s) throws SavanException;
/**
* To retrieve a previously stored subscriber.
*
* @param subscriberID
* @return
* @throws SavanException
*/
Subscriber retrieve(String subscriberID) throws SavanException;
/**
* To retrieve all subscribers stored upto now.
*
* @return
* @throws SavanException
*/
Iterator retrieveAllSubscribers() throws SavanException;
Iterator retrieveAllSubscriberGroups() throws SavanException;
/**
* To delete a previously stored subscriber.
*
* @param subscriberID
* @throws SavanException
*/
void delete(String subscriberID) throws SavanException;
SubscriberGroup getSubscriberGroup(String groupId) throws SavanException;
void addSubscriberGroup(String subscriberList) throws SavanException;
void addSubscriberToGroup (String groupId, Subscriber subscriber) throws SavanException;
}
| 6,331 |
0 | Create_ds/axis-axis2-java-savan/modules/core/src/main/java/org/apache/savan | Create_ds/axis-axis2-java-savan/modules/core/src/main/java/org/apache/savan/storage/DefaultSubscriberStore.java | /*
* Copyright 1999-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.savan.storage;
import org.apache.axis2.context.ConfigurationContext;
import org.apache.savan.SavanException;
import org.apache.savan.subscribers.Subscriber;
import org.apache.savan.subscribers.SubscriberGroup;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
public class DefaultSubscriberStore implements SubscriberStore {
private HashMap subscriberMap = null;
private HashMap subscriberGroups = null;
public DefaultSubscriberStore() {
subscriberMap = new HashMap();
subscriberGroups = new HashMap();
}
public void init(ConfigurationContext configurationContext) throws SavanException {
// TODO Auto-generated method stub
}
public Subscriber retrieve(String id) {
return (Subscriber)subscriberMap.get(id);
}
public void store(Subscriber s) {
URI subscriberID = s.getId();
String key = subscriberID.toString();
subscriberMap.put(key, s);
}
public void delete(String subscriberID) {
subscriberMap.remove(subscriberID);
}
public Iterator retrieveAllSubscribers() {
ArrayList allSubscribers = new ArrayList();
for (Iterator iter = subscriberMap.keySet().iterator(); iter.hasNext();) {
Object key = iter.next();
allSubscribers.add(subscriberMap.get(key));
}
return allSubscribers.iterator();
}
public Iterator retrieveAllSubscriberGroups() {
ArrayList allSubscriberGroups = new ArrayList();
for (Iterator iter = subscriberGroups.keySet().iterator(); iter.hasNext();) {
Object key = iter.next();
allSubscriberGroups.add(subscriberGroups.get(key));
}
return allSubscriberGroups.iterator();
}
public void addSubscriberGroup(String groupId) {
subscriberGroups.put(groupId, new SubscriberGroup());
}
public void addSubscriberToGroup(String listId, Subscriber subscriber) throws SavanException {
SubscriberGroup subscriberGroup = (SubscriberGroup)subscriberGroups.get(listId);
if (subscriberGroup != null)
subscriberGroup.addSubscriber(subscriber);
else
throw new SavanException("Cannot find the Subscriber store");
}
public SubscriberGroup getSubscriberGroup(String groupId) {
return (SubscriberGroup)subscriberGroups.get(groupId);
}
}
| 6,332 |
0 | Create_ds/axis-axis2-java-savan/modules/core/src/main/java/org/apache/savan | Create_ds/axis-axis2-java-savan/modules/core/src/main/java/org/apache/savan/subscription/RenewBean.java | /*
* Copyright 1999-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.savan.subscription;
/** Encapsulates a data for a subscrpition renewal. */
public class RenewBean {
long renewMount;
String subscriberID;
public long getRenewMount() {
return renewMount;
}
public String getSubscriberID() {
return subscriberID;
}
public void setRenewMount(long renewMount) {
this.renewMount = renewMount;
}
public void setSubscriberID(String subscriberID) {
this.subscriberID = subscriberID;
}
}
| 6,333 |
0 | Create_ds/axis-axis2-java-savan/modules/core/src/main/java/org/apache/savan | Create_ds/axis-axis2-java-savan/modules/core/src/main/java/org/apache/savan/subscription/ExpirationBean.java | /*
* Copyright 1999-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.savan.subscription;
import org.apache.axis2.databinding.types.Duration;
import java.util.Date;
/** Defines a expiration. Could be based on a specific time in the future or a duration. */
public class ExpirationBean {
Date dateValue;
Duration durationValue;
String subscriberID;
boolean duration;
public String getSubscriberID() {
return subscriberID;
}
public void setSubscriberID(String subscriberID) {
this.subscriberID = subscriberID;
}
public boolean isDuration() {
return duration;
}
public void setDuration(boolean duration) {
this.duration = duration;
}
public Date getDateValue() {
return dateValue;
}
public Duration getDurationValue() {
return durationValue;
}
public void setDateValue(Date dateValue) {
this.dateValue = dateValue;
}
public void setDurationValue(Duration durationValue) {
this.durationValue = durationValue;
}
}
| 6,334 |
0 | Create_ds/axis-axis2-java-savan/modules/core/src/main/java/org/apache/savan | Create_ds/axis-axis2-java-savan/modules/core/src/main/java/org/apache/savan/subscription/SubscriptionProcessor.java | /*
* Copyright 1999-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.savan.subscription;
import org.apache.axiom.soap.SOAPEnvelope;
import org.apache.axis2.context.ServiceContext;
import org.apache.savan.SavanException;
import org.apache.savan.SavanMessageContext;
import org.apache.savan.publication.client.PublicationClient;
import org.apache.savan.storage.SubscriberStore;
import org.apache.savan.subscribers.Subscriber;
import org.apache.savan.util.CommonUtil;
/** Abstractly defines subscription methods. Each protocol may extend this to add its own work. */
public abstract class SubscriptionProcessor {
public abstract void init(SavanMessageContext smc) throws SavanException;
public void unsubscribe(SavanMessageContext endSubscriptionMessage) throws SavanException {
String subscriberID = getSubscriberID(endSubscriptionMessage);
if (subscriberID == null) {
String message = "Cannot find the subscriber ID";
throw new SavanException(message);
}
SubscriberStore store = endSubscriptionMessage.getSubscriberStore();
if (store == null)
throw new SavanException("AbstractSubscriber store not found");
store.delete(subscriberID);
}
public void renewSubscription(SavanMessageContext renewMessage) throws SavanException {
SubscriberStore store = renewMessage.getSubscriberStore();
if (store == null)
throw new SavanException("AbstractSubscriber store not found");
ExpirationBean bean = getExpirationBean(renewMessage);
Subscriber subscriber = store.retrieve(bean.getSubscriberID());
if (subscriber == null) {
throw new SavanException("Given subscriber is not present");
}
subscriber.renewSubscription(bean);
}
public void subscribe(SavanMessageContext subscriptionMessage) throws SavanException {
SubscriberStore store = subscriptionMessage.getSubscriberStore();
if (store == null)
throw new SavanException("Sabscriber store not found");
Subscriber subscriber = getSubscriberFromMessage(subscriptionMessage);
store.store(subscriber);
}
public void endSubscription(String subscriberID, String reason, ServiceContext serviceContext)
throws SavanException {
SubscriberStore store = CommonUtil.getSubscriberStore(serviceContext.getAxisService());
if (store == null) {
throw new SavanException("SubscriberStore not found");
}
Subscriber subscriber = store.retrieve(subscriberID);
if (subscriber == null) {
throw new SavanException("No such subscriber '" + subscriberID + "'");
}
// doProtocolSpecificEndSubscription(subscriber,reason,serviceContext.getConfigurationContext());
store.delete(subscriberID);
}
public void publish(SavanMessageContext publishMessage) throws SavanException {
//TODO handle Topics
SOAPEnvelope requestEnvelope = publishMessage.getEnvelope();
ServiceContext serviceContext = publishMessage.getMessageContext().getServiceContext();
PublicationClient client = new PublicationClient(serviceContext.getConfigurationContext());
client.sendPublication(requestEnvelope.getBody().getFirstElement(),
serviceContext.getAxisService(), null);
}
public void getStatus(SavanMessageContext smc) {
}
public abstract void pauseSubscription(SavanMessageContext pauseSubscriptionMessage)
throws SavanException;
public abstract void resumeSubscription(SavanMessageContext resumeSubscriptionMessage)
throws SavanException;
public abstract Subscriber getSubscriberFromMessage(SavanMessageContext smc)
throws SavanException;
public abstract ExpirationBean getExpirationBean(SavanMessageContext renewMessage)
throws SavanException;
public abstract String getSubscriberID(SavanMessageContext smc) throws SavanException;
}
| 6,335 |
0 | Create_ds/axis-axis2-java-savan/modules/core/src/main/java/org/apache/savan | Create_ds/axis-axis2-java-savan/modules/core/src/main/java/org/apache/savan/subscribers/Subscriber.java | /*
* Copyright 1999-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.savan.subscribers;
import org.apache.axiom.om.OMElement;
import org.apache.savan.SavanException;
import org.apache.savan.subscription.ExpirationBean;
import java.net.URI;
/**
* Defines a subscriber which is the entity that define a specific subscription in savan.
* Independent of the protocol type.
*/
public interface Subscriber {
public URI getId();
public void setId(URI id);
public void sendEventData(OMElement eventData) throws SavanException;
public void renewSubscription(ExpirationBean bean);
}
| 6,336 |
0 | Create_ds/axis-axis2-java-savan/modules/core/src/main/java/org/apache/savan | Create_ds/axis-axis2-java-savan/modules/core/src/main/java/org/apache/savan/subscribers/SubscriberGroup.java | /*
* Copyright 1999-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.savan.subscribers;
import org.apache.axiom.om.OMElement;
import org.apache.savan.SavanException;
import java.net.URI;
import java.util.ArrayList;
import java.util.Iterator;
/** Defines a set of subscribers that are acting as a group or a Topic. */
public class SubscriberGroup {
protected ArrayList subscribers = null;
private URI id;
public URI getId() {
return id;
}
public void setId(URI id) {
this.id = id;
}
public SubscriberGroup() {
subscribers = new ArrayList();
}
public void addSubscriber(Subscriber subscriber) throws SavanException {
subscribers.add(subscriber);
}
public void sendEventDataToGroup(OMElement eventData) throws SavanException {
for (Iterator it = subscribers.iterator(); it.hasNext();) {
Subscriber subscriber = (Subscriber)it.next();
subscriber.sendEventData(eventData);
}
}
}
| 6,337 |
0 | Create_ds/axis-axis2-java-savan/modules/core/src/main/java/org/apache/savan | Create_ds/axis-axis2-java-savan/modules/core/src/main/java/org/apache/savan/eventing/EventingSubscriptionProcessor.java | /*
* Copyright 1999-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.savan.eventing;
import org.apache.axiom.om.OMAttribute;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMNode;
import org.apache.axiom.om.util.UUIDGenerator;
import org.apache.axiom.soap.SOAPBody;
import org.apache.axiom.soap.SOAPEnvelope;
import org.apache.axiom.soap.SOAPHeader;
import org.apache.axis2.AxisFault;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.addressing.EndpointReferenceHelper;
import org.apache.axis2.databinding.types.Duration;
import org.apache.axis2.databinding.utils.ConverterUtil;
import org.apache.savan.SavanConstants;
import org.apache.savan.SavanException;
import org.apache.savan.SavanMessageContext;
import org.apache.savan.configuration.ConfigurationManager;
import org.apache.savan.configuration.Protocol;
import org.apache.savan.configuration.SubscriberBean;
import org.apache.savan.eventing.subscribers.EventingSubscriber;
import org.apache.savan.filters.Filter;
import org.apache.savan.subscribers.Subscriber;
import org.apache.savan.subscription.ExpirationBean;
import org.apache.savan.subscription.SubscriptionProcessor;
import org.apache.savan.util.CommonUtil;
import org.apache.savan.util.UtilFactory;
import javax.xml.namespace.QName;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Calendar;
import java.util.Date;
public class EventingSubscriptionProcessor extends SubscriptionProcessor {
public void init(SavanMessageContext smc) throws SavanException {
//setting the subscriber_id as a property if possible.
String id = getSubscriberID(smc);
if (id != null) {
smc.setProperty(EventingConstants.TransferedProperties.SUBSCRIBER_UUID, id);
}
}
public Subscriber getSubscriberFromMessage(SavanMessageContext smc) throws SavanException {
ConfigurationManager configurationManager = (ConfigurationManager)smc
.getConfigurationContext().getProperty(SavanConstants.CONFIGURATION_MANAGER);
if (configurationManager == null)
throw new SavanException("Configuration Manager not set");
Protocol protocol = smc.getProtocol();
if (protocol == null)
throw new SavanException("Protocol not found");
UtilFactory utilFactory = protocol.getUtilFactory();
SOAPEnvelope envelope = smc.getEnvelope();
if (envelope == null)
return null;
// AbstractSubscriber subscriber = utilFactory.createSubscriber(); //eventing only works on leaf subscriber for now.
String subscriberName = protocol.getDefaultSubscriber();
SubscriberBean subscriberBean = configurationManager.getSubscriberBean(subscriberName);
Subscriber subscriber = configurationManager.getSubscriberInstance(subscriberName);
if (!(subscriber instanceof EventingSubscriber)) {
String message =
"Eventing protocol only support implementations of eventing subscriber as Subscribers";
throw new SavanException(message);
}
EventingSubscriber eventingSubscriber = (EventingSubscriber)subscriber;
String id = UUIDGenerator.getUUID();
smc.setProperty(EventingConstants.TransferedProperties.SUBSCRIBER_UUID, id);
try {
URI uri = new URI(id);
eventingSubscriber.setId(uri);
} catch (URISyntaxException e) {
throw new SavanException(e);
}
SOAPBody body = envelope.getBody();
OMElement subscribeElement = body.getFirstChildWithName(new QName(
EventingConstants.EVENTING_NAMESPACE, EventingConstants.ElementNames.Subscribe));
if (subscribeElement == null)
throw new SavanException("'Subscribe' element is not present");
OMElement endToElement = subscribeElement.getFirstChildWithName(new QName(
EventingConstants.EVENTING_NAMESPACE, EventingConstants.ElementNames.EndTo));
if (endToElement != null) {
EndpointReference endToEPR = null;
try {
endToEPR = EndpointReferenceHelper.fromOM(endToElement);
}
catch (AxisFault af) {
throw new SavanException(af);
}
eventingSubscriber.setEndToEPr(endToEPR);
}
OMElement deliveryElement = subscribeElement.getFirstChildWithName(new QName(
EventingConstants.EVENTING_NAMESPACE, EventingConstants.ElementNames.Delivery));
if (deliveryElement == null)
throw new SavanException("Delivery element is not present");
OMElement notifyToElement = deliveryElement.getFirstChildWithName(new QName(
EventingConstants.EVENTING_NAMESPACE, EventingConstants.ElementNames.NotifyTo));
if (notifyToElement == null)
throw new SavanException("NotifyTo element is null");
EndpointReference notifyToEPr = null;
try {
notifyToEPr = EndpointReferenceHelper.fromOM(notifyToElement);
}
catch (AxisFault af) {
throw new SavanException(af);
}
OMAttribute deliveryModeAttr =
deliveryElement.getAttribute(new QName(EventingConstants.ElementNames.Mode));
String deliveryMode = null;
if (deliveryModeAttr != null) {
deliveryMode = deliveryModeAttr.getAttributeValue().trim();
} else {
deliveryMode = EventingConstants.DEFAULT_DELIVERY_MODE;
}
if (!deliveryModesupported()) {
//TODO throw unsupported delivery mode fault.
}
Delivery delivery = new Delivery();
delivery.setDeliveryEPR(notifyToEPr);
delivery.setDeliveryMode(deliveryMode);
eventingSubscriber.setDelivery(delivery);
OMElement expiresElement =
subscribeElement.getFirstChildWithName(EventingConstants.EXPIRES_QNAME);
if (expiresElement != null) {
String expiresText = expiresElement.getText();
if (expiresText == null) {
String message = "Expires Text is null";
throw new SavanException(message);
}
expiresText = expiresText.trim();
ExpirationBean expirationBean = getExpirationBeanFromString(expiresText);
Date expiration = null;
if (expirationBean.isDuration()) {
Calendar calendar = Calendar.getInstance();
CommonUtil.addDurationToCalendar(calendar, expirationBean.getDurationValue());
expiration = calendar.getTime();
} else
expiration = expirationBean.getDateValue();
if (expiration == null) {
String message = "Cannot understand the given date-time value for the Expiration";
throw new SavanException(message);
}
eventingSubscriber.setSubscriptionEndingTime(expiration);
} else {
// They didn't specify an expiration, so default to an hour.
Calendar calendar = Calendar.getInstance();
Duration duration = new Duration();
duration.setHours(1);
CommonUtil.addDurationToCalendar(calendar, duration);
eventingSubscriber.setSubscriptionEndingTime(calendar.getTime());
}
OMElement filterElement = subscribeElement.getFirstChildWithName(new QName(
EventingConstants.EVENTING_NAMESPACE, EventingConstants.ElementNames.Filter));
if (filterElement != null) {
OMNode filterNode = filterElement.getFirstOMChild();
OMAttribute dialectAttr =
filterElement.getAttribute(new QName(EventingConstants.ElementNames.Dialect));
Filter filter = null;
String filterKey = EventingConstants.DEFAULT_FILTER_IDENTIFIER;
if (dialectAttr != null) {
filterKey = dialectAttr.getAttributeValue();
}
filter = configurationManager.getFilterInstanceFromId(filterKey);
if (filter == null)
throw new SavanException("The Filter defined by the dialect is not available");
filter.setUp(filterNode);
eventingSubscriber.setFilter(filter);
}
return eventingSubscriber;
}
public void pauseSubscription(SavanMessageContext pauseSubscriptionMessage)
throws SavanException {
throw new UnsupportedOperationException(
"Eventing specification does not support this type of messages");
}
public void resumeSubscription(SavanMessageContext resumeSubscriptionMessage)
throws SavanException {
throw new UnsupportedOperationException(
"Eventing specification does not support this type of messages");
}
public ExpirationBean getExpirationBean(SavanMessageContext renewMessage)
throws SavanException {
SOAPEnvelope envelope = renewMessage.getEnvelope();
SOAPBody body = envelope.getBody();
ExpirationBean expirationBean = null;
OMElement renewElement = body.getFirstChildWithName(new QName(
EventingConstants.EVENTING_NAMESPACE, EventingConstants.ElementNames.Renew));
if (renewElement == null) {
String message = "Renew element not present in the assumed Renew Message";
throw new SavanException(message);
}
OMElement expiresElement = renewElement.getFirstChildWithName(new QName(
EventingConstants.EVENTING_NAMESPACE, EventingConstants.ElementNames.Expires));
if (expiresElement != null) {
String expiresText = expiresElement.getText().trim();
expirationBean = getExpirationBeanFromString(expiresText);
}
String subscriberID = getSubscriberID(renewMessage);
if (subscriberID == null) {
String message = "Cannot find the subscriber ID";
throw new SavanException(message);
}
renewMessage
.setProperty(EventingConstants.TransferedProperties.SUBSCRIBER_UUID, subscriberID);
expirationBean.setSubscriberID(subscriberID);
return expirationBean;
}
public String getSubscriberID(SavanMessageContext smc) throws SavanException {
SOAPEnvelope envelope = smc.getEnvelope();
SOAPHeader header = envelope.getHeader();
if (header == null) {
return null;
}
OMElement ideltifierElement = envelope.getHeader().getFirstChildWithName(new QName(
EventingConstants.EVENTING_NAMESPACE, EventingConstants.ElementNames.Identifier));
if (ideltifierElement == null) {
return null;
}
return ideltifierElement.getText().trim();
}
private ExpirationBean getExpirationBeanFromString(String expiresStr) throws SavanException {
ExpirationBean bean = new ExpirationBean();
//expires can be a duration or a date time.
//Doing the conversion using the ConverUtil helper class.
Date date = null;
boolean isDuration = CommonUtil.isDuration(expiresStr);
if (isDuration) {
try {
bean.setDuration(true);
Duration duration = ConverterUtil.convertToDuration(expiresStr);
bean.setDurationValue(duration);
} catch (IllegalArgumentException e) {
String message = "Cannot convert the Expiration value to a valid duration";
throw new SavanException(message, e);
}
} else {
try {
Calendar calendar = ConverterUtil.convertToDateTime(expiresStr);
date = calendar.getTime();
bean.setDateValue(date);
} catch (Exception e) {
String message = "Cannot convert the Expiration value to a valid DATE/TIME";
throw new SavanException(message, e);
}
}
boolean invalidExpirationTime = false;
if (bean.isDuration()) {
if (isInvalidDiration(bean.getDurationValue()))
invalidExpirationTime = true;
} else {
if (isDateInThePast(bean.getDateValue()))
invalidExpirationTime = true;
}
if (invalidExpirationTime) {
//TODO throw Invalid Expiration Time fault
}
return bean;
}
private boolean deliveryModesupported() {
return true;
}
private boolean isInvalidDiration(Duration duration) {
return false;
}
private boolean isDateInThePast(Date date) {
return false;
}
private boolean filterDilalectSupported(String filterDialect) {
return true;
}
}
| 6,338 |
0 | Create_ds/axis-axis2-java-savan/modules/core/src/main/java/org/apache/savan | Create_ds/axis-axis2-java-savan/modules/core/src/main/java/org/apache/savan/eventing/EventingMessageReceiverDelegator.java | /*
* Copyright 1999-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.savan.eventing;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMNamespace;
import org.apache.axiom.soap.SOAPEnvelope;
import org.apache.axiom.soap.SOAPFactory;
import org.apache.axis2.AxisFault;
import org.apache.axis2.addressing.AddressingConstants;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.addressing.EndpointReferenceHelper;
import org.apache.axis2.context.MessageContext;
import org.apache.axis2.databinding.utils.ConverterUtil;
import org.apache.savan.SavanConstants;
import org.apache.savan.SavanException;
import org.apache.savan.SavanMessageContext;
import org.apache.savan.eventing.subscribers.EventingSubscriber;
import org.apache.savan.messagereceiver.MessageReceiverDelegator;
import org.apache.savan.storage.SubscriberStore;
import org.apache.savan.subscribers.Subscriber;
import org.apache.savan.util.CommonUtil;
import javax.xml.namespace.QName;
import java.util.Calendar;
import java.util.Date;
public class EventingMessageReceiverDelegator extends MessageReceiverDelegator {
public void doProtocolSpecificProcessing(SavanMessageContext inSavanMessage,
MessageContext outMessage) throws SavanException {
int messageType = inSavanMessage.getMessageType();
if (messageType == SavanConstants.MessageTypes.SUBSCRIPTION_MESSAGE) {
handleSubscriptionRequest(inSavanMessage, outMessage);
} else if (messageType == SavanConstants.MessageTypes.RENEW_MESSAGE) {
handleRenewRequest(inSavanMessage, outMessage);
} else if (messageType == SavanConstants.MessageTypes.UNSUBSCRIPTION_MESSAGE) {
handleEndSubscriptionRequest(inSavanMessage, outMessage);
} else if (messageType == SavanConstants.MessageTypes.GET_STATUS_MESSAGE) {
handleGetStatusRequest(inSavanMessage, outMessage);
}
}
private void handleSubscriptionRequest(SavanMessageContext subscriptionMessage,
MessageContext outMessage) throws SavanException {
if (outMessage == null)
throw new SavanException("Missing outMessage for Subscribe");
MessageContext subscriptionMsgCtx = subscriptionMessage.getMessageContext();
SOAPEnvelope outMessageEnvelope = outMessage.getEnvelope();
SOAPFactory factory;
if (outMessageEnvelope != null) {
factory = (SOAPFactory)outMessageEnvelope.getOMFactory();
} else {
factory = (SOAPFactory)subscriptionMsgCtx.getEnvelope().getOMFactory();
outMessageEnvelope = factory.getDefaultEnvelope();
try {
outMessage.setEnvelope(outMessageEnvelope);
} catch (AxisFault e) {
throw new SavanException(e);
}
}
//setting the action
outMessage.getOptions().setAction(EventingConstants.Actions.SubscribeResponse);
//sending the subscription response message.
String address = subscriptionMsgCtx.getOptions().getTo().getAddress();
EndpointReference subscriptionManagerEPR = new EndpointReference(address);
String id = (String)subscriptionMessage
.getProperty(EventingConstants.TransferedProperties.SUBSCRIBER_UUID);
if (id == null)
throw new SavanException("Subscription UUID is not set");
subscriptionManagerEPR.addReferenceParameter(
new QName(EventingConstants.EVENTING_NAMESPACE,
EventingConstants.ElementNames.Identifier,
EventingConstants.EVENTING_PREFIX),
id);
OMNamespace ens = factory.createOMNamespace(EventingConstants.EVENTING_NAMESPACE,
EventingConstants.EVENTING_PREFIX);
OMElement subscribeResponseElement =
factory.createOMElement(EventingConstants.ElementNames.SubscribeResponse, ens);
OMElement subscriptionManagerElement;
try {
subscriptionManagerElement = EndpointReferenceHelper.toOM(
subscribeResponseElement.getOMFactory(),
subscriptionManagerEPR,
new QName(EventingConstants.EVENTING_NAMESPACE,
EventingConstants.ElementNames.SubscriptionManager,
EventingConstants.EVENTING_PREFIX),
AddressingConstants.Submission.WSA_NAMESPACE);
} catch (AxisFault e) {
throw new SavanException(e);
}
//TODO set expires
subscribeResponseElement.addChild(subscriptionManagerElement);
outMessageEnvelope.getBody().addChild(subscribeResponseElement);
//setting the message type
outMessage.setProperty(SavanConstants.MESSAGE_TYPE,
SavanConstants.MessageTypes.SUBSCRIPTION_RESPONSE_MESSAGE);
}
private void handleRenewRequest(SavanMessageContext renewMessage, MessageContext outMessage)
throws SavanException {
if (outMessage == null)
throw new SavanException("Missing outMessage for Renew");
MessageContext subscriptionMsgCtx = renewMessage.getMessageContext();
SOAPEnvelope outMessageEnvelope = outMessage.getEnvelope();
SOAPFactory factory;
if (outMessageEnvelope != null) {
factory = (SOAPFactory)outMessageEnvelope.getOMFactory();
} else {
factory = (SOAPFactory)subscriptionMsgCtx.getEnvelope().getOMFactory();
outMessageEnvelope = factory.getDefaultEnvelope();
try {
outMessage.setEnvelope(outMessageEnvelope);
} catch (AxisFault e) {
throw new SavanException(e);
}
}
//setting the action
outMessage.getOptions().setAction(EventingConstants.Actions.RenewResponse);
OMNamespace ens = factory.createOMNamespace(EventingConstants.EVENTING_NAMESPACE,
EventingConstants.EVENTING_PREFIX);
//sending the Renew Response message.
OMElement renewResponseElement =
factory.createOMElement(EventingConstants.ElementNames.RenewResponse, ens);
String subscriberID = (String)renewMessage
.getProperty(EventingConstants.TransferedProperties.SUBSCRIBER_UUID);
if (subscriberID == null) {
String message = "SubscriberID TransferedProperty is not set";
throw new SavanException(message);
}
SubscriberStore store =
CommonUtil.getSubscriberStore(renewMessage.getMessageContext().getAxisService());
Subscriber subscriber = store.retrieve(subscriberID);
EventingSubscriber eventingSubscriber = (EventingSubscriber)subscriber;
if (eventingSubscriber == null) {
String message = "Cannot find the AbstractSubscriber with the given ID";
throw new SavanException(message);
}
Date expiration = eventingSubscriber.getSubscriptionEndingTime();
Calendar calendar = Calendar.getInstance();
calendar.setTime(expiration);
String expiresValue = ConverterUtil.convertToString(calendar);
if (expiresValue != null) {
OMElement expiresElement =
factory.createOMElement(EventingConstants.ElementNames.Expires, ens);
renewResponseElement.addChild(expiresElement);
}
outMessageEnvelope.getBody().addChild(renewResponseElement);
//setting the message type
outMessage.setProperty(SavanConstants.MESSAGE_TYPE,
SavanConstants.MessageTypes.RENEW_RESPONSE_MESSAGE);
}
private void handleEndSubscriptionRequest(SavanMessageContext renewMessage,
MessageContext outMessage) throws SavanException {
if (outMessage == null)
throw new SavanException("Missing outMessage for EndSubscription");
MessageContext subscriptionMsgCtx = renewMessage.getMessageContext();
//setting the action
outMessage.getOptions().setAction(EventingConstants.Actions.UnsubscribeResponse);
SOAPEnvelope outMessageEnvelope = outMessage.getEnvelope();
if (outMessageEnvelope == null) {
SOAPFactory factory;
factory = (SOAPFactory)subscriptionMsgCtx.getEnvelope().getOMFactory();
outMessageEnvelope = factory.getDefaultEnvelope();
try {
outMessage.setEnvelope(outMessageEnvelope);
} catch (AxisFault e) {
throw new SavanException(e);
}
}
//setting the message type
outMessage.setProperty(SavanConstants.MESSAGE_TYPE,
SavanConstants.MessageTypes.UNSUBSCRIPTION_RESPONSE_MESSAGE);
}
public void handleGetStatusRequest(SavanMessageContext getStatusMessage,
MessageContext outMessage) throws SavanException {
if (outMessage == null)
throw new SavanException("Missing outMessage for getStatus!");
MessageContext getStatusContext = getStatusMessage.getMessageContext();
String id = (String)getStatusMessage
.getProperty(EventingConstants.TransferedProperties.SUBSCRIBER_UUID);
if (id == null)
throw new SavanException("Subscriber ID not found");
//setting the action
outMessage.getOptions().setAction(EventingConstants.Actions.GetStatusResponse);
SOAPEnvelope outMessageEnvelope = outMessage.getEnvelope();
SOAPFactory factory;
if (outMessageEnvelope != null) {
factory = (SOAPFactory)outMessageEnvelope.getOMFactory();
} else {
factory = (SOAPFactory)getStatusContext.getEnvelope().getOMFactory();
outMessageEnvelope = factory.getDefaultEnvelope();
try {
outMessage.setEnvelope(outMessageEnvelope);
} catch (AxisFault e) {
throw new SavanException(e);
}
}
SubscriberStore store = CommonUtil
.getSubscriberStore(getStatusMessage.getMessageContext().getAxisService());
if (store == null) {
throw new SavanException("AbstractSubscriber Store was not found");
}
EventingSubscriber subscriber = (EventingSubscriber)store.retrieve(id);
if (subscriber == null) {
throw new SavanException("AbstractSubscriber not found");
}
OMNamespace ens = factory.createOMNamespace(EventingConstants.EVENTING_NAMESPACE,
EventingConstants.EVENTING_PREFIX);
OMElement getStatusResponseElement =
factory.createOMElement(EventingConstants.ElementNames.GetStatusResponse, ens);
Date expires = subscriber.getSubscriptionEndingTime();
if (expires != null) {
OMElement expiresElement =
factory.createOMElement(EventingConstants.ElementNames.Expires, ens);
Calendar calendar = Calendar.getInstance();
calendar.setTime(expires);
String expirationString = ConverterUtil.convertToString(calendar);
expiresElement.setText(expirationString);
getStatusResponseElement.addChild(expiresElement);
}
outMessageEnvelope.getBody().addChild(getStatusResponseElement);
//setting the message type
outMessage.setProperty(SavanConstants.MESSAGE_TYPE,
SavanConstants.MessageTypes.GET_STATUS_RESPONSE_MESSAGE);
}
public void doProtocolSpecificProcessing(SavanMessageContext inSavanMessage)
throws SavanException {
}
}
| 6,339 |
0 | Create_ds/axis-axis2-java-savan/modules/core/src/main/java/org/apache/savan | Create_ds/axis-axis2-java-savan/modules/core/src/main/java/org/apache/savan/eventing/Delivery.java | /*
* Copyright 1999-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.savan.eventing;
import org.apache.axis2.addressing.EndpointReference;
public class Delivery {
EndpointReference deliveryEPR;
String deliveryMode;
public EndpointReference getDeliveryEPR() {
return deliveryEPR;
}
public String getDeliveryMode() {
return deliveryMode;
}
public void setDeliveryEPR(EndpointReference deliveryEPR) {
this.deliveryEPR = deliveryEPR;
}
public void setDeliveryMode(String deliveryMode) {
this.deliveryMode = deliveryMode;
}
}
| 6,340 |
0 | Create_ds/axis-axis2-java-savan/modules/core/src/main/java/org/apache/savan | Create_ds/axis-axis2-java-savan/modules/core/src/main/java/org/apache/savan/eventing/EventingUtilFactory.java | /*
* Copyright 1999-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.savan.eventing;
import org.apache.axis2.context.MessageContext;
import org.apache.savan.SavanConstants;
import org.apache.savan.SavanMessageContext;
import org.apache.savan.eventing.subscribers.EventingSubscriber;
import org.apache.savan.messagereceiver.MessageReceiverDelegator;
import org.apache.savan.subscribers.Subscriber;
import org.apache.savan.subscription.SubscriptionProcessor;
import org.apache.savan.util.UtilFactory;
public class EventingUtilFactory implements UtilFactory {
public SavanMessageContext initializeMessage(SavanMessageContext smc) {
MessageContext messageContext = smc.getMessageContext();
//setting the message type.
String action = messageContext.getOptions().getAction();
if (EventingConstants.Actions.Subscribe.equals(action))
smc.setMessageType(SavanConstants.MessageTypes.SUBSCRIPTION_MESSAGE);
else if (EventingConstants.Actions.Renew.equals(action))
smc.setMessageType(SavanConstants.MessageTypes.RENEW_MESSAGE);
else if (EventingConstants.Actions.Unsubscribe.equals(action))
smc.setMessageType(SavanConstants.MessageTypes.UNSUBSCRIPTION_MESSAGE);
else if (EventingConstants.Actions.GetStatus.equals(action))
smc.setMessageType(SavanConstants.MessageTypes.GET_STATUS_MESSAGE);
else if (EventingConstants.Actions.SubscribeResponse.equals(action))
smc.setMessageType(SavanConstants.MessageTypes.SUBSCRIPTION_RESPONSE_MESSAGE);
else if (EventingConstants.Actions.RenewResponse.equals(action))
smc.setMessageType(SavanConstants.MessageTypes.RENEW_RESPONSE_MESSAGE);
else if (EventingConstants.Actions.UnsubscribeResponse.equals(action))
smc.setMessageType(SavanConstants.MessageTypes.UNSUBSCRIPTION_RESPONSE_MESSAGE);
else if (EventingConstants.Actions.GetStatusResponse.equals(action))
smc.setMessageType(SavanConstants.MessageTypes.GET_STATUS_RESPONSE_MESSAGE);
else if (EventingConstants.Actions.Publish.equals(action))
smc.setMessageType(SavanConstants.MessageTypes.PUBLISH);
else
smc.setMessageType(SavanConstants.MessageTypes.UNKNOWN);
return smc;
}
public SubscriptionProcessor createSubscriptionProcessor() {
return new EventingSubscriptionProcessor();
}
public MessageReceiverDelegator createMessageReceiverDelegator() {
return new EventingMessageReceiverDelegator();
}
public Subscriber createSubscriber() {
return new EventingSubscriber();
}
}
| 6,341 |
0 | Create_ds/axis-axis2-java-savan/modules/core/src/main/java/org/apache/savan | Create_ds/axis-axis2-java-savan/modules/core/src/main/java/org/apache/savan/eventing/EventingConstants.java | /*
* Copyright 1999-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.savan.eventing;
import javax.xml.namespace.QName;
public interface EventingConstants {
String EVENTING_NAMESPACE = "http://schemas.xmlsoap.org/ws/2004/08/eventing";
String EXTENDED_EVENTING_NAMESPACE = "http://ws.apache.org/ws/2007/05/eventing-extended";
String EVENTING_PREFIX = "wse";
String DEFAULT_DELIVERY_MODE =
"http://schemas.xmlsoap.org/ws/2004/08/eventing/DeliveryModes/Push";
String DEFAULT_FILTER_IDENTIFIER = FilterDialects.XPath;
QName EXPIRES_QNAME = new QName(
EventingConstants.EVENTING_NAMESPACE, EventingConstants.ElementNames.Expires);
interface TransferedProperties {
String SUBSCRIBER_UUID = "SAVAN_EVENTING_SUBSCRIBER_UUID";
}
interface ElementNames {
String Subscribe = "Subscribe";
String EndTo = "EndTo";
String Delivery = "Delivery";
String Mode = "Mode";
String NotifyTo = "NotifyTo";
String Expires = "Expires";
String Filter = "Filter";
String Dialect = "Dialect";
String SubscribeResponse = "SubscribeResponse";
String SubscriptionManager = "SubscriptionManager";
String Renew = "Renew";
String RenewResponse = "RenewResponse";
String Identifier = "Identifier";
String Unsubscribe = "Unsubscribe";
String GetStatus = "GetStatus";
String GetStatusResponse = "GetStatusResponse";
String Topic = "topic";
}
interface Actions {
String Subscribe = "http://schemas.xmlsoap.org/ws/2004/08/eventing/Subscribe";
String SubscribeResponse =
"http://schemas.xmlsoap.org/ws/2004/08/eventing/SubscribeResponse";
String Renew = "http://schemas.xmlsoap.org/ws/2004/08/eventing/Renew";
String RenewResponse = "http://schemas.xmlsoap.org/ws/2004/08/eventing/RenewResponse";
String Unsubscribe = "http://schemas.xmlsoap.org/ws/2004/08/eventing/Unsubscribe";
String UnsubscribeResponse =
"http://schemas.xmlsoap.org/ws/2004/08/eventing/UnsubscribeResponse";
String GetStatus = "http://schemas.xmlsoap.org/ws/2004/08/eventing/GetStatus";
String GetStatusResponse =
"http://schemas.xmlsoap.org/ws/2004/08/eventing/GetStatusResponse";
String Publish = "http://ws.apache.org/ws/2007/05/eventing-extended/Publish";
}
interface Properties {
String SOAPVersion = "SOAPVersion";
}
interface FilterDialects {
String XPath = "http://www.w3.org/TR/1999/REC-xpath-19991116";
}
}
| 6,342 |
0 | Create_ds/axis-axis2-java-savan/modules/core/src/main/java/org/apache/savan/eventing | Create_ds/axis-axis2-java-savan/modules/core/src/main/java/org/apache/savan/eventing/subscribers/EventingSubscriber.java | /*
* Copyright 2004,2005 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.savan.eventing.subscribers;
import org.apache.axiom.om.OMElement;
import org.apache.axis2.AxisFault;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.client.Options;
import org.apache.axis2.client.ServiceClient;
import org.apache.axis2.context.ConfigurationContext;
import org.apache.axis2.context.MessageContext;
import org.apache.savan.SavanException;
import org.apache.savan.eventing.Delivery;
import org.apache.savan.filters.Filter;
import org.apache.savan.subscribers.Subscriber;
import org.apache.savan.subscription.ExpirationBean;
import org.apache.savan.util.CommonUtil;
import java.net.URI;
import java.util.Calendar;
import java.util.Date;
/** Defines methods common to all eventing subscribers. */
public class EventingSubscriber implements Subscriber {
private URI id;
private Filter filter = null;
private EndpointReference endToEPr;
private Delivery delivery;
private ConfigurationContext configurationContext;
/** The time at which further notification of messages should be avaoded to this subscriber. */
private Date subscriptionEndingTime = null;
public Filter getFilter() {
return filter;
}
public void setFilter(Filter filter) {
this.filter = filter;
}
public URI getId() {
return id;
}
public void setId(URI id) {
this.id = id;
}
public Delivery getDelivery() {
return delivery;
}
public EndpointReference getEndToEPr() {
return endToEPr;
}
public void setDelivery(Delivery delivery) {
this.delivery = delivery;
}
public void setEndToEPr(EndpointReference errorReportingEPR) {
this.endToEPr = errorReportingEPR;
}
public Date getSubscriptionEndingTime() {
return subscriptionEndingTime;
}
public void setSubscriptionEndingTime() {
}
public ConfigurationContext getConfigurationContext() {
return configurationContext;
}
public void setConfigurationContext(ConfigurationContext configurationContext) {
this.configurationContext = configurationContext;
}
public void setSubscriptionEndingTime(Date subscriptionEndingTime) {
this.subscriptionEndingTime = subscriptionEndingTime;
}
/**
* This method first checks whether the passed message complies with the current filter.
* If so the message is sent, and the subscriberID is added to the PublicationReport.
* Otherwise the message is ignored.
*
* @param eventData an OMElement containing the SOAP Envelope
* @throws SavanException
*/
public void sendEventData(OMElement eventData) throws SavanException {
Date date = new Date();
boolean expired = false;
if (subscriptionEndingTime != null && date.after(subscriptionEndingTime))
expired = true;
if (expired) {
String message = "Cant notify the listener since the subscription has been expired";
throw new SavanException(message);
}
if (doesEventDataBelongToTheFilter(eventData)) {
sendThePublication(eventData);
}
}
private boolean doesEventDataBelongToTheFilter(OMElement eventData) throws SavanException {
return filter == null || filter.checkCompliance(eventData);
}
private void sendThePublication(OMElement eventData) throws SavanException {
EndpointReference deliveryEPR = delivery.getDeliveryEPR();
try {
ServiceClient sc = new ServiceClient(configurationContext, null);
Options options = new Options();
sc.setOptions(options);
options.setTo(deliveryEPR);
options.setProperty(MessageContext.TRANSPORT_NON_BLOCKING, Boolean.FALSE);
sc.fireAndForget(eventData);
} catch (AxisFault e) {
throw new SavanException(e);
}
}
public void renewSubscription(ExpirationBean bean) {
if (bean.isDuration()) {
if (subscriptionEndingTime == null) {
Calendar calendar = Calendar.getInstance();
CommonUtil.addDurationToCalendar(calendar, bean.getDurationValue());
subscriptionEndingTime = calendar.getTime();
} else {
Calendar expiration = Calendar.getInstance();
expiration.setTime(subscriptionEndingTime);
CommonUtil.addDurationToCalendar(expiration, bean.getDurationValue());
subscriptionEndingTime = expiration.getTime();
}
} else
subscriptionEndingTime = bean.getDateValue();
}
}
| 6,343 |
0 | Create_ds/axis-axis2-java-savan/modules/core/src/main/java/org/apache/savan/eventing | Create_ds/axis-axis2-java-savan/modules/core/src/main/java/org/apache/savan/eventing/client/SubscriptionStatus.java | /*
* Copyright 2004,2005 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.savan.eventing.client;
public class SubscriptionStatus {
String expirationValue;
public String getExpirationValue() {
return expirationValue;
}
public void setExpirationValue(String expirationValue) {
this.expirationValue = expirationValue;
}
}
| 6,344 |
0 | Create_ds/axis-axis2-java-savan/modules/core/src/main/java/org/apache/savan/eventing | Create_ds/axis-axis2-java-savan/modules/core/src/main/java/org/apache/savan/eventing/client/EventingClientBean.java | /*
* Copyright 1999-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.savan.eventing.client;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.databinding.types.Duration;
import java.util.Date;
public class EventingClientBean {
EndpointReference deliveryEPR;
EndpointReference endToEPR;
String filterDialect;
String filter;
Date expirationTime;
Duration expirationDuration;
public Duration getExpirationDuration() {
return expirationDuration;
}
public void setExpirationDuration(Duration expirationDuration) {
this.expirationDuration = expirationDuration;
}
public EndpointReference getDeliveryEPR() {
return deliveryEPR;
}
public EndpointReference getEndToEPR() {
return endToEPR;
}
public Date getExpirationTime() {
return expirationTime;
}
public String getFilter() {
return filter;
}
public String getFilterDialect() {
return filterDialect;
}
public void setDeliveryEPR(EndpointReference deliveryEPR) {
this.deliveryEPR = deliveryEPR;
}
public void setEndToEPR(EndpointReference endToEPR) {
this.endToEPR = endToEPR;
}
public void setExpirationTime(Date expirationTime) {
this.expirationTime = expirationTime;
}
public void setFilter(String filter) {
this.filter = filter;
}
public void setFilterDialect(String filterDialect) {
this.filterDialect = filterDialect;
}
}
| 6,345 |
0 | Create_ds/axis-axis2-java-savan/modules/core/src/main/java/org/apache/savan/eventing | Create_ds/axis-axis2-java-savan/modules/core/src/main/java/org/apache/savan/eventing/client/SubscriptionResponseData.java | /*
* Copyright 1999-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.savan.eventing.client;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.savan.subscription.ExpirationBean;
public class SubscriptionResponseData {
EndpointReference subscriptionManager = null;
ExpirationBean expiration = null;
public SubscriptionResponseData() {
expiration = new ExpirationBean();
}
public EndpointReference getSubscriptionManager() {
return subscriptionManager;
}
public ExpirationBean getExpiration() {
return expiration;
}
public void setExpiration(ExpirationBean expiration) {
this.expiration = expiration;
}
public void setSubscriptionManager(EndpointReference subscriptionManager) {
this.subscriptionManager = subscriptionManager;
}
}
| 6,346 |
0 | Create_ds/axis-axis2-java-savan/modules/core/src/main/java/org/apache/savan/eventing | Create_ds/axis-axis2-java-savan/modules/core/src/main/java/org/apache/savan/eventing/client/EventingClient.java | /*
* Copyright 1999-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.savan.eventing.client;
import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMAttribute;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMNamespace;
import org.apache.axiom.soap.*;
import org.apache.axis2.addressing.AddressingConstants;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.addressing.EndpointReferenceHelper;
import org.apache.axis2.client.Options;
import org.apache.axis2.client.ServiceClient;
import org.apache.axis2.databinding.types.Duration;
import org.apache.axis2.databinding.utils.ConverterUtil;
import org.apache.savan.eventing.EventingConstants;
import org.apache.savan.subscription.ExpirationBean;
import org.apache.savan.util.CommonUtil;
import javax.xml.namespace.QName;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
public class EventingClient {
ServiceClient serviceClient = null;
HashMap subscriptionDataMap = null;
public EventingClient(ServiceClient serviceClient) {
this.serviceClient = serviceClient;
subscriptionDataMap = new HashMap();
}
public void subscribe(EventingClientBean bean, String subscriptionID) throws Exception {
Options options = serviceClient.getOptions();
if (options == null) {
options = new Options();
serviceClient.setOptions(options);
}
String SOAPVersion = options.getSoapVersionURI();
if (SOAPVersion == null)
SOAPVersion = SOAP11Constants.SOAP_ENVELOPE_NAMESPACE_URI;
SOAPEnvelope envelope = createSubscriptionEnvelope(bean, SOAPVersion);
String oldAction = options.getAction();
String action = EventingConstants.Actions.Subscribe;
options.setAction(action);
OMElement subscriptionResponse =
serviceClient.sendReceive(envelope.getBody().getFirstElement());
SubscriptionResponseData subscriptionResponseData =
getSubscriptionResponseData(subscriptionResponse);
subscriptionDataMap.put(subscriptionID, subscriptionResponseData);
options.setAction(oldAction);
}
public void renewSubscription(Date newExpirationTime, String subscriptionID) throws Exception {
String expirationString = ConverterUtil.convertToString(newExpirationTime);
renewSubscription(expirationString, subscriptionID);
}
public void renewSubscription(Duration duration, String subscriptionID) throws Exception {
String expirationString = ConverterUtil.convertToString(duration);
renewSubscription(expirationString, subscriptionID);
}
private void renewSubscription(String expirationString, String subscriptionID)
throws Exception {
SubscriptionResponseData data =
(SubscriptionResponseData)subscriptionDataMap.get(subscriptionID);
EndpointReference managerEPR = data.getSubscriptionManager();
if (managerEPR == null)
throw new Exception("Manager EPR is not set");
Options options = serviceClient.getOptions();
if (options == null) {
options = new Options();
serviceClient.setOptions(options);
}
String SOAPVersion = options.getSoapVersionURI();
if (SOAPVersion == null)
SOAPVersion = SOAP11Constants.SOAP_ENVELOPE_NAMESPACE_URI;
SOAPEnvelope envelope = createRenewSubscriptionEnvelope(expirationString, SOAPVersion);
String oldAction = options.getAction();
String action = EventingConstants.Actions.Renew;
options.setAction(action);
EndpointReference oldTo = serviceClient.getOptions().getTo();
options.setTo(managerEPR);
OMElement renewResponse = serviceClient.sendReceive(envelope.getBody().getFirstElement());
options.setAction(oldAction);
options.setTo(oldTo);
}
public void unsubscribe(String subscriptionID) throws Exception {
SubscriptionResponseData data =
(SubscriptionResponseData)subscriptionDataMap.get(subscriptionID);
EndpointReference managerEPR = data.getSubscriptionManager();
if (managerEPR == null)
throw new Exception("Manager EPR is not set");
Options options = serviceClient.getOptions();
if (options == null) {
options = new Options();
serviceClient.setOptions(options);
}
String SOAPVersion = options.getSoapVersionURI();
if (SOAPVersion == null)
SOAPVersion = SOAP11Constants.SOAP_ENVELOPE_NAMESPACE_URI;
SOAPEnvelope envelope = createUnsubscriptionEnvelope(SOAPVersion);
String oldAction = options.getAction();
String action = EventingConstants.Actions.Unsubscribe;
options.setAction(action);
EndpointReference oldTo = serviceClient.getOptions().getTo();
options.setTo(managerEPR);
OMElement unsubscribeResponse =
serviceClient.sendReceive(envelope.getBody().getFirstElement());
//TODO process unsubscriber response
options.setAction(oldAction);
options.setTo(oldTo);
}
public SubscriptionStatus getSubscriptionStatus(String subscriptionID) throws Exception {
SubscriptionResponseData data =
(SubscriptionResponseData)subscriptionDataMap.get(subscriptionID);
EndpointReference managerEPR = data.getSubscriptionManager();
if (managerEPR == null)
throw new Exception("Manager EPR is not set");
Options options = serviceClient.getOptions();
if (options == null) {
options = new Options();
serviceClient.setOptions(options);
}
String SOAPVersion = options.getSoapVersionURI();
if (SOAPVersion == null)
SOAPVersion = SOAP11Constants.SOAP_ENVELOPE_NAMESPACE_URI;
SOAPEnvelope envelope = createGetStatusEnvelope(SOAPVersion);
String oldAction = options.getAction();
String action = EventingConstants.Actions.GetStatus;
options.setAction(action);
EndpointReference oldTo = serviceClient.getOptions().getTo();
options.setTo(managerEPR);
OMElement getStatusResponse =
serviceClient.sendReceive(envelope.getBody().getFirstElement());
SubscriptionStatus subscriptionStatus = getSubscriptionStatus(getStatusResponse);
options.setAction(oldAction);
options.setTo(oldTo);
return subscriptionStatus;
}
private SubscriptionResponseData getSubscriptionResponseData(OMElement responseMessagePayload)
throws Exception {
SubscriptionResponseData data = new SubscriptionResponseData();
OMElement subscriberManagerElement = responseMessagePayload.getFirstChildWithName(new QName(
EventingConstants.EVENTING_NAMESPACE,
EventingConstants.ElementNames.SubscriptionManager));
EndpointReference managerEPR = EndpointReferenceHelper.fromOM(subscriberManagerElement);
data.setSubscriptionManager(managerEPR);
OMElement expiresElement = responseMessagePayload.getFirstChildWithName(new QName(
EventingConstants.EVENTING_NAMESPACE, EventingConstants.ElementNames.Expires));
if (expiresElement != null) {
String text = expiresElement.getText().trim();
ExpirationBean expirationBean = new ExpirationBean();
if (CommonUtil.isDuration(text)) {
expirationBean.setDuration(true);
Duration duration = ConverterUtil.convertToDuration(text);
expirationBean.setDurationValue(duration);
} else {
expirationBean.setDuration(false);
Date date = ConverterUtil.convertToDateTime(text).getTime();
expirationBean.setDateValue(date);
}
data.setExpiration(expirationBean);
}
return data;
}
private SubscriptionStatus getSubscriptionStatus(OMElement getStatusResponseElement)
throws Exception {
SubscriptionStatus subscriptionStatus = new SubscriptionStatus();
OMElement expiresElementElement = getStatusResponseElement.getFirstChildWithName(new QName(
EventingConstants.EVENTING_NAMESPACE, EventingConstants.ElementNames.Expires));
if (expiresElementElement != null) {
String valueStr = expiresElementElement.getText();
// long expires = Long.parseLong(valueStr);
subscriptionStatus.setExpirationValue(valueStr);
}
return subscriptionStatus;
}
private SOAPEnvelope createSubscriptionEnvelope(EventingClientBean bean, String SOAPVersion)
throws Exception {
SOAPFactory factory = null;
if (SOAP11Constants.SOAP_ENVELOPE_NAMESPACE_URI.equals(SOAPVersion))
factory = OMAbstractFactory.getSOAP11Factory();
else if (SOAP12Constants.SOAP_ENVELOPE_NAMESPACE_URI.equals(SOAPVersion))
factory = OMAbstractFactory.getSOAP12Factory();
else throw new Exception("Unknown SOAP version");
SOAPEnvelope envelope = factory.getDefaultEnvelope();
SOAPBody body = envelope.getBody();
OMNamespace ens = factory.createOMNamespace(EventingConstants.EVENTING_NAMESPACE,
EventingConstants.EVENTING_PREFIX);
OMElement subscriptionElement =
factory.createOMElement(EventingConstants.ElementNames.Subscribe, ens);
EndpointReference endToEPR = bean.getEndToEPR();
if (bean.getEndToEPR() != null) {
OMElement endToElement = EndpointReferenceHelper.toOM(
subscriptionElement.getOMFactory(), endToEPR, new QName(
EventingConstants.EVENTING_NAMESPACE, EventingConstants.ElementNames.EndTo,
EventingConstants.EVENTING_PREFIX),
AddressingConstants.Submission.WSA_NAMESPACE);
subscriptionElement.addChild(endToElement);
}
EndpointReference deliveryEPR = bean.getDeliveryEPR();
if (deliveryEPR == null)
throw new Exception("Delivery EPR is not set");
OMElement deliveryElement =
factory.createOMElement(EventingConstants.ElementNames.Delivery, ens);
OMElement notifyToElement = EndpointReferenceHelper.toOM(subscriptionElement.getOMFactory(),
deliveryEPR, new QName(
EventingConstants.EVENTING_NAMESPACE, EventingConstants.ElementNames.NotifyTo,
EventingConstants.EVENTING_PREFIX), AddressingConstants.Submission.WSA_NAMESPACE);
deliveryElement.addChild(notifyToElement);
subscriptionElement.addChild(deliveryElement);
if (bean.getExpirationTime() != null || bean.getExpirationDuration() != null) {
String timeString = null;
//if time is set it will be taken. Otherwise duration will be taken.
if (bean.getExpirationTime() != null) {
Date date = bean.getExpirationTime();
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
timeString = ConverterUtil.convertToString(calendar);
} else if (bean.getExpirationDuration() != null) {
Duration duration = bean.getExpirationDuration();
timeString = ConverterUtil.convertToString(duration);
}
OMElement expiresElement =
factory.createOMElement(EventingConstants.ElementNames.Expires, ens);
expiresElement.setText(timeString);
subscriptionElement.addChild(expiresElement);
}
if (bean.getFilter() != null) {
String filter = bean.getFilter();
String dialect = bean.getFilterDialect();
OMElement filterElement =
factory.createOMElement(EventingConstants.ElementNames.Filter, ens);
OMAttribute dialectAttr = factory.createOMAttribute(
EventingConstants.ElementNames.Dialect, null, dialect);
filterElement.addAttribute(dialectAttr);
filterElement.setText(filter);
subscriptionElement.addChild(filterElement);
}
body.addChild(subscriptionElement);
return envelope;
}
private SOAPEnvelope createRenewSubscriptionEnvelope(String expiresString, String SOAPVersion)
throws Exception {
SOAPFactory factory = null;
if (SOAP11Constants.SOAP_ENVELOPE_NAMESPACE_URI.equals(SOAPVersion))
factory = OMAbstractFactory.getSOAP11Factory();
else if (SOAP12Constants.SOAP_ENVELOPE_NAMESPACE_URI.equals(SOAPVersion))
factory = OMAbstractFactory.getSOAP12Factory();
else throw new Exception("Unknown SOAP version");
SOAPEnvelope envelope = factory.getDefaultEnvelope();
SOAPBody body = envelope.getBody();
OMNamespace ens = factory.createOMNamespace(EventingConstants.EVENTING_NAMESPACE,
EventingConstants.EVENTING_PREFIX);
OMElement renewElement = factory.createOMElement(EventingConstants.ElementNames.Renew, ens);
OMElement expiresElement =
factory.createOMElement(EventingConstants.ElementNames.Expires, ens);
expiresElement.setText(expiresString);
renewElement.addChild(expiresElement);
body.addChild(renewElement);
return envelope;
}
private SOAPEnvelope createUnsubscriptionEnvelope(String SOAPVersion) throws Exception {
SOAPFactory factory = null;
if (SOAP11Constants.SOAP_ENVELOPE_NAMESPACE_URI.equals(SOAPVersion))
factory = OMAbstractFactory.getSOAP11Factory();
else if (SOAP12Constants.SOAP_ENVELOPE_NAMESPACE_URI.equals(SOAPVersion))
factory = OMAbstractFactory.getSOAP12Factory();
else throw new Exception("Unknown SOAP version");
SOAPEnvelope envelope = factory.getDefaultEnvelope();
SOAPBody body = envelope.getBody();
OMNamespace ens = factory.createOMNamespace(EventingConstants.EVENTING_NAMESPACE,
EventingConstants.EVENTING_PREFIX);
OMElement unsubscribeElement =
factory.createOMElement(EventingConstants.ElementNames.Unsubscribe, ens);
body.addChild(unsubscribeElement);
return envelope;
}
private SOAPEnvelope createGetStatusEnvelope(String SOAPVersion) throws Exception {
SOAPFactory factory = null;
if (SOAP11Constants.SOAP_ENVELOPE_NAMESPACE_URI.equals(SOAPVersion))
factory = OMAbstractFactory.getSOAP11Factory();
else if (SOAP12Constants.SOAP_ENVELOPE_NAMESPACE_URI.equals(SOAPVersion))
factory = OMAbstractFactory.getSOAP12Factory();
else throw new Exception("Unknown SOAP version");
SOAPEnvelope envelope = factory.getDefaultEnvelope();
SOAPBody body = envelope.getBody();
OMNamespace ens = factory.createOMNamespace(EventingConstants.EVENTING_NAMESPACE,
EventingConstants.EVENTING_PREFIX);
OMElement getStatusElement =
factory.createOMElement(EventingConstants.ElementNames.GetStatus, ens);
body.addChild(getStatusElement);
return envelope;
}
}
| 6,347 |
0 | Create_ds/axis-axis2-java-savan/modules/samples/eventing/src/sample | Create_ds/axis-axis2-java-savan/modules/samples/eventing/src/sample/eventing/Client.java | /*
* Copyright 2004,2005 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.eventing;
import org.apache.axis2.AxisFault;
import org.apache.axis2.description.AxisService;
import org.apache.axis2.transport.http.SimpleHTTPServer;
import org.apache.axis2.engine.AxisServer;
import org.apache.axis2.engine.AxisConfiguration;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.client.Options;
import org.apache.axis2.client.ServiceClient;
import org.apache.axis2.context.ConfigurationContext;
import org.apache.axis2.context.ConfigurationContextFactory;
import org.apache.savan.eventing.client.EventingClient;
import org.apache.savan.eventing.client.EventingClientBean;
import org.apache.savan.eventing.client.SubscriptionStatus;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Client {
boolean done = false;
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
private final int MIN_OPTION = 1;
private final int MAX_OPTION = 9;
private final String SUBSCRIBER_1_ID = "subscriber1";
private final String SUBSCRIBER_2_ID = "subscriber2";
private EventingClient eventingClient = null;
private String toAddressPart = "/axis2/services/PublisherService";
private String listener1AddressPart = "/axis2/services/ListenerService1";
private String listener2AddressPart = "/axis2/services/ListenerService2";
private static String repo = null;
private static int port = 8080;
private static String serverIP = "127.0.0.1";
private static final String portParam = "-p";
private static final String repoParam = "-r";
private static final String helpParam = "-h";
public static void main(String[] args) throws Exception {
for (String arg : args) {
if (helpParam.equalsIgnoreCase(arg)) {
displayHelp();
System.exit(0);
}
}
String portStr = getParam(portParam, args);
if (portStr != null) {
port = Integer.parseInt(portStr);
System.out.println("Server Port was set to:" + port);
}
String repoStr = getParam(repoParam, args);
if (repoStr != null) {
repo = repoStr;
System.out.println("Client Repository was set to:" + repo);
}
Client c = new Client();
c.run();
}
private static void displayHelp() {
System.out.println("Help page for the Eventing Client");
System.out.println("---------------------------------");
System.out.println("Set the client reposiory using the parameter -r");
System.out.println("Set the server port using the parameter -p");
}
static void foo() throws Exception {
ConfigurationContext ctx = ConfigurationContextFactory.createDefaultConfigurationContext();
SimpleHTTPServer server = new SimpleHTTPServer(ctx, 7071);
AxisConfiguration axisConfig = ctx.getAxisConfiguration();
// AxisService service = new AxisService("ListenerService1");
// svc.addParameter("ServiceClass", ListenerService1.class.getName());
AxisService service = AxisService.createService(ListenerService1.class.getName(),
axisConfig);
axisConfig.addService(service);
server.start();
}
/**
* This will check the given parameter in the array and will return, if available
*
* @param param
* @param args
* @return
*/
private static String getParam(String param, String[] args) {
if (param == null || "".equals(param)) {
return null;
}
for (int i = 0; i < args.length; i = i + 2) {
String arg = args[i];
if (param.equalsIgnoreCase(arg) && (args.length >= (i + 1))) {
return args[i + 1];
}
}
return null;
}
public void run() throws Exception {
System.out.println("\n");
System.out.println("Welcome to Axis2 Eventing Sample");
System.out.println("================================\n");
foo();
boolean validOptionSelected = false;
int selectedOption = -1;
while (!validOptionSelected) {
displayMenu();
selectedOption = getIntInput();
if (selectedOption >= MIN_OPTION && selectedOption <= MAX_OPTION)
validOptionSelected = true;
else
System.out.println("\nInvalid Option \n\n");
}
initClient();
performAction(selectedOption);
//TODO publish
// System.out.println("Press enter to initialize the publisher service.");
// reader.readLine();
//
// options.setAction("uuid:DummyMethodAction");
// serviceClient.fireAndForget(getDummyMethodRequestElement());
while (!done) {
validOptionSelected = false;
selectedOption = -1;
while (!validOptionSelected) {
displayMenu();
selectedOption = getIntInput();
if (selectedOption >= MIN_OPTION && selectedOption <= MAX_OPTION)
validOptionSelected = true;
else
System.out.println("\nInvalid Option \n\n");
}
performAction(selectedOption);
}
}
private void displayMenu() {
System.out.println("Press 1 to subscribe Listener Service 1");
System.out.println("Press 2 to subscribe Listener Service 2");
System.out.println("Press 3 to subscribe both listener services");
System.out.println("Press 4 to unsubscribe Listener Service 1");
System.out.println("Press 5 to unsubscribe Listener Service 2");
System.out.println("Press 6 to unsubscribe both listener services");
System.out.println("Press 7 to to get the status of the subscription to Service 1");
System.out.println("Press 8 to to get the status of the subscription to Service 2");
System.out.println("Press 9 to Exit");
}
private int getIntInput() throws IOException {
String option = reader.readLine();
try {
return Integer.parseInt(option);
} catch (NumberFormatException e) {
//invalid option
return -1;
}
}
private void initClient() throws AxisFault {
String CLIENT_REPO = null;
if (repo != null) {
CLIENT_REPO = repo;
} else {
// throw new AxisFault ("Please specify the client repository as a program argument.Use '-h' for help.");
}
ConfigurationContext configContext = ConfigurationContextFactory
.createConfigurationContextFromFileSystem(CLIENT_REPO, null);
ServiceClient serviceClient = new ServiceClient(configContext, null);
Options options = new Options();
serviceClient.setOptions(options);
serviceClient.engageModule("addressing");
eventingClient = new EventingClient(serviceClient);
String toAddress = "http://" + serverIP + ":" + port + toAddressPart;
options.setTo(new EndpointReference(toAddress));
}
private void performAction(int action) throws Exception {
switch (action) {
case 1:
doSubscribe(SUBSCRIBER_1_ID);
break;
case 2:
doSubscribe(SUBSCRIBER_2_ID);
break;
case 3:
doSubscribe(SUBSCRIBER_1_ID);
doSubscribe(SUBSCRIBER_2_ID);
break;
case 4:
doUnsubscribe(SUBSCRIBER_1_ID);
break;
case 5:
doUnsubscribe(SUBSCRIBER_2_ID);
break;
case 6:
doUnsubscribe(SUBSCRIBER_1_ID);
doUnsubscribe(SUBSCRIBER_2_ID);
break;
case 7:
doGetStatus(SUBSCRIBER_1_ID);
break;
case 8:
doGetStatus(SUBSCRIBER_2_ID);
break;
case 9:
done = true;
break;
default:
break;
}
}
private void doSubscribe(String ID) throws Exception {
EventingClientBean bean = new EventingClientBean();
String subscribingAddress = null;
if (SUBSCRIBER_1_ID.equals(ID)) {
subscribingAddress = "http://" + serverIP + ":" + 7070 + listener1AddressPart;
} else if (SUBSCRIBER_2_ID.equals(ID)) {
subscribingAddress = "http://" + serverIP + ":" + port + listener2AddressPart;
}
bean.setDeliveryEPR(new EndpointReference(subscribingAddress));
//uncomment following to set an expiration time of 10 minutes.
// Date date = new Date ();
// date.setMinutes(date.getMinutes()+10);
// bean.setExpirationTime(date);
eventingClient.subscribe(bean, ID);
Thread.sleep(1000); //TODO remove if not sequired
}
private void doUnsubscribe(String ID) throws Exception {
eventingClient.unsubscribe(ID);
Thread.sleep(1000); //TODO remove if not sequired
}
private void doGetStatus(String ID) throws Exception {
SubscriptionStatus status = eventingClient.getSubscriptionStatus(ID);
Thread.sleep(1000); //TODO remove if not sequired
String statusValue = status.getExpirationValue();
System.out.println("Status of the subscriber '" + ID + "' is" + statusValue);
}
// private OMElement getDummyMethodRequestElement() {
// OMFactory fac = OMAbstractFactory.getOMFactory();
// OMNamespace namespace = fac.createOMNamespace(applicationNamespaceName, "ns1");
// return fac.createOMElement(dummyMethod, namespace);
// }
}
| 6,348 |
0 | Create_ds/axis-axis2-java-savan/modules/samples/eventing/src/sample | Create_ds/axis-axis2-java-savan/modules/samples/eventing/src/sample/eventing/ListenerService2.java | /*
* Copyright 2004,2005 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.eventing;
import org.apache.axiom.om.OMElement;
public class ListenerService2 {
String name = "ListenerService2";
public void publish(OMElement param) throws Exception {
System.out.println("\n");
System.out.println("'" + name + "' got a new publication...");
System.out.println(param);
System.out.println("\n");
}
}
| 6,349 |
0 | Create_ds/axis-axis2-java-savan/modules/samples/eventing/src/sample | Create_ds/axis-axis2-java-savan/modules/samples/eventing/src/sample/eventing/PublisherService.java | /*
* Copyright 2004,2005 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.eventing;
import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMFactory;
import org.apache.axiom.om.OMNamespace;
import org.apache.axis2.AxisFault;
import org.apache.axis2.context.ServiceContext;
import org.apache.savan.publication.client.PublicationClient;
import org.apache.savan.storage.SubscriberStore;
import org.apache.savan.util.CommonUtil;
import java.util.Random;
public class PublisherService {
ServiceContext serviceContext = null;
public void init(ServiceContext serviceContext) throws AxisFault {
System.out.println("Eventing Service INIT called");
this.serviceContext = serviceContext;
PublisherThread thread = new PublisherThread();
thread.start();
}
public void dummyMethod(OMElement param) throws Exception {
System.out.println("Eventing Service dummy method called, woo!");
}
private class PublisherThread extends Thread {
String Publication = "Publication";
// String publicationNamespaceValue = "http://tempuri/publication/";
String publicationNamespaceValue = "http://eventing.sample";
Random r = new Random();
public void run() {
try {
while (true) {
Thread.sleep(5000);
//publishing
SubscriberStore store =
CommonUtil.getSubscriberStore(serviceContext.getAxisService());
if (store != null) {
System.out.println("Publishing next publication...");
OMElement data = getNextPublicationData();
PublicationClient publicationClient =
new PublicationClient(serviceContext.getConfigurationContext());
publicationClient.sendPublication(data, serviceContext.getAxisService(),
null);
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public OMElement getNextPublicationData() {
OMFactory factory = OMAbstractFactory.getOMFactory();
OMNamespace namespace = factory.createOMNamespace(publicationNamespaceValue, "ns1");
OMElement publicationElement = factory.createOMElement(Publication, namespace);
int value = r.nextInt();
publicationElement.setText(Integer.toString(value));
OMElement data = factory.createOMElement("publish", namespace);
data.addChild(publicationElement);
return data;
}
}
}
| 6,350 |
0 | Create_ds/axis-axis2-java-savan/modules/samples/eventing/src/sample | Create_ds/axis-axis2-java-savan/modules/samples/eventing/src/sample/eventing/ListenerService1.java | /*
* Copyright 2004,2005 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.eventing;
import org.apache.axiom.om.OMElement;
public class ListenerService1 {
String name = "ListenerService1";
public void publish(OMElement param) throws Exception {
System.out.println("\n");
System.out.println("'" + name + "' got a new publication...");
System.out.println(param);
System.out.println("\n");
}
}
| 6,351 |
0 | Create_ds/heap-dump-tool/src/test/java/com/paypal | Create_ds/heap-dump-tool/src/test/java/com/paypal/heapdumptool/ApplicationTest.java | package com.paypal.heapdumptool;
import com.paypal.heapdumptool.Application.VersionProvider;
import com.paypal.heapdumptool.capture.PrivilegeEscalator;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.MockedStatic;
import org.springframework.boot.test.system.CapturedOutput;
import org.springframework.boot.test.system.OutputCaptureExtension;
import static com.paypal.heapdumptool.ApplicationTestSupport.runApplication;
import static com.paypal.heapdumptool.ApplicationTestSupport.runApplicationPrivileged;
import static com.paypal.heapdumptool.capture.PrivilegeEscalator.escalatePrivilegesIfNeeded;
import static com.paypal.heapdumptool.capture.PrivilegeEscalator.Escalation.ESCALATED;
import static com.paypal.heapdumptool.fixture.ResourceTool.contentOf;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mockStatic;
@ExtendWith(OutputCaptureExtension.class)
public class ApplicationTest {
@Test
public void testVersionProvider() throws Exception {
final String[] version = new VersionProvider().getVersion();
assertThat(version[0]).contains("heap-dump-tool");
}
@Test
public void testMainHelp(final CapturedOutput output) throws Exception {
final int exitCode = runApplicationPrivileged("help");
assertThat(exitCode).isEqualTo(0);
final String expectedOutput = contentOf(getClass(), "help.txt");
assertThat(output).isEqualTo(expectedOutput);
}
@Test
public void testPrivilegeEscalated(final CapturedOutput output) throws Exception {
try (final MockedStatic<PrivilegeEscalator> mocked = mockStatic(PrivilegeEscalator.class)) {
mocked.when(() -> escalatePrivilegesIfNeeded("help"))
.thenReturn(ESCALATED);
final int exitCode = runApplication("help");
assertThat(exitCode).isEqualTo(0);
assertThat(output).isEmpty();
}
}
}
| 6,352 |
0 | Create_ds/heap-dump-tool/src/test/java/com/paypal | Create_ds/heap-dump-tool/src/test/java/com/paypal/heapdumptool/ApplicationTestSupport.java | package com.paypal.heapdumptool;
import com.paypal.heapdumptool.capture.PrivilegeEscalator;
import org.apache.commons.lang3.mutable.MutableInt;
import org.mockito.MockedStatic;
import static com.paypal.heapdumptool.capture.PrivilegeEscalator.Escalation.PRIVILEGED_ALREADY;
import static com.paypal.heapdumptool.fixture.MockitoTool.voidAnswer;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.Mockito.mockStatic;
public class ApplicationTestSupport {
public static int runApplication(final String... args) throws Exception {
final MutableInt exitCode = new MutableInt();
try (final MockedStatic<Application> applicationMock = mockStatic(Application.class)) {
applicationMock.when(() -> Application.systemExit(anyInt()))
.thenAnswer(voidAnswer());
applicationMock.when(() -> Application.main(args))
.thenCallRealMethod();
Application.main(args);
}
return exitCode.getValue();
}
public static int runApplicationPrivileged(final String... args) throws Exception {
try (final MockedStatic<PrivilegeEscalator> escalatorMock = mockStatic(PrivilegeEscalator.class)) {
escalatorMock.when(() -> PrivilegeEscalator.escalatePrivilegesIfNeeded(any()))
.thenReturn(PRIVILEGED_ALREADY);
return runApplication(args);
}
}
private ApplicationTestSupport() {
throw new AssertionError();
}
}
| 6,353 |
0 | Create_ds/heap-dump-tool/src/test/java/com/paypal/heapdumptool | Create_ds/heap-dump-tool/src/test/java/com/paypal/heapdumptool/capture/CaptureCommandTest.java | package com.paypal.heapdumptool.capture;
import com.paypal.heapdumptool.sanitizer.DataSize;
import org.junit.jupiter.api.Test;
import org.meanbean.test.BeanVerifier;
import static org.assertj.core.api.Assertions.assertThat;
public class CaptureCommandTest {
@Test
public void testBean() {
BeanVerifier.forClass(CaptureCommand.class)
.withSettings(settings -> settings.addOverridePropertyFactory(CaptureCommand::getBufferSize, () -> DataSize.ofMegabytes(5)))
.verifyGettersAndSetters();
}
@Test
public void testSanitizationText() {
assertThat(escapedSanitizationText("\\0"))
.isEqualTo("\0");
assertThat(escapedSanitizationText("\0"))
.isEqualTo("\0");
assertThat(escapedSanitizationText("foobar"))
.isEqualTo("foobar");
}
private String escapedSanitizationText(final String sanitizationText) {
final CaptureCommand cmd = new CaptureCommand();
cmd.setSanitizationText(sanitizationText);
return cmd.getSanitizationText();
}
}
| 6,354 |
0 | Create_ds/heap-dump-tool/src/test/java/com/paypal/heapdumptool | Create_ds/heap-dump-tool/src/test/java/com/paypal/heapdumptool/capture/CaptureStreamFactoryTest.java | package com.paypal.heapdumptool.capture;
import com.paypal.heapdumptool.sanitizer.SanitizeCommand;
import org.apache.commons.compress.utils.IOUtils;
import org.apache.commons.io.output.CloseShieldOutputStream;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.DynamicTest;
import org.junit.jupiter.api.TestFactory;
import org.junit.jupiter.api.io.TempDir;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collection;
import java.util.concurrent.LinkedBlockingQueue;
import static com.paypal.heapdumptool.sanitizer.DataSize.ofBytes;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.DynamicTest.dynamicTest;
import static org.mockito.Mockito.mock;
public class CaptureStreamFactoryTest {
@TempDir
Path tempDir;
private final Collection<Closeable> closeables = new LinkedBlockingQueue<>();
@AfterEach
public void afterEach() {
closeables.forEach(IOUtils::closeQuietly);
}
@TestFactory
public DynamicTest[] streamFactoryTests() {
final InputStream inputStream = mock(InputStream.class);
return new DynamicTest[] {
dynamicTest("New InputStream", () -> {
final CaptureStreamFactory streamFactory = newStreamFactory(inputStream);
assertThat(streamFactory.newInputStream(null))
.isSameAs(inputStream);
}),
dynamicTest("New OutputStream", () -> {
final CaptureStreamFactory streamFactory = newStreamFactory(inputStream);
assertThat(streamFactory.newOutputStream())
.isInstanceOf(CloseShieldOutputStream.class);
assertThat(streamFactory.getNativeOutputStream())
.isInstanceOf(nioOutputStreamType());
}),
};
}
private Class<?> nioOutputStreamType() throws IOException {
final OutputStream nioOutputStream = Files.newOutputStream(tempDir.resolve("baz"));
closeables.add(nioOutputStream);
return nioOutputStream.getClass();
}
private CaptureStreamFactory newStreamFactory(final InputStream inputStream) {
final SanitizeCommand command = new SanitizeCommand();
command.setInputFile(tempDir.resolve("foo"));
command.setOutputFile(tempDir.resolve("bar"));
command.setBufferSize(ofBytes(0));
final CaptureStreamFactory captureStreamFactory = new CaptureStreamFactory(command, inputStream);
closeables.add(captureStreamFactory);
return captureStreamFactory;
}
}
| 6,355 |
0 | Create_ds/heap-dump-tool/src/test/java/com/paypal/heapdumptool | Create_ds/heap-dump-tool/src/test/java/com/paypal/heapdumptool/capture/PrivilegeEscalatorTest.java | package com.paypal.heapdumptool.capture;
import com.google.common.io.Closer;
import com.paypal.heapdumptool.fixture.ConstructorTester;
import com.paypal.heapdumptool.fixture.ResourceTool;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.io.TempDir;
import org.mockito.MockedStatic;
import org.springframework.boot.test.system.CapturedOutput;
import org.springframework.boot.test.system.OutputCaptureExtension;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import static com.paypal.heapdumptool.capture.PrivilegeEscalator.escalatePrivilegesIfNeeded;
import static com.paypal.heapdumptool.capture.PrivilegeEscalator.Escalation.ESCALATED;
import static com.paypal.heapdumptool.capture.PrivilegeEscalator.Escalation.PRIVILEGED_ALREADY;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.Mockito.mockStatic;
@ExtendWith(OutputCaptureExtension.class)
public class PrivilegeEscalatorTest {
@TempDir
Path tempDir;
private final Closer closer = Closer.create();
@BeforeEach
@AfterEach
public void tearDown() throws IOException {
closer.close();
}
@Test
public void testNotInDockerContainer() throws Exception {
final Path cgroupPath = Paths.get(copyCgroup("native-cgroup.txt"));
final MockedStatic<Paths> mocked = createStaticMock(Paths.class);
expectCgroup(mocked, cgroupPath);
assertThat(escalatePrivilegesIfNeeded("foo", "b a r"))
.isEqualTo(PRIVILEGED_ALREADY);
}
@Test
public void testInDockerContainerPrivilegedAlready() throws Exception {
final Path cgroupPath = Paths.get(copyCgroup("docker-cgroup.txt"));
final Path replacementPath = Paths.get("/bin/echo");
final MockedStatic<Paths> mocked = createStaticMock(Paths.class);
expectCgroup(mocked, cgroupPath);
expectNsenter1(mocked, replacementPath);
assertThat(escalatePrivilegesIfNeeded("foo", "b a r"))
.isEqualTo(PRIVILEGED_ALREADY);
}
@Test
public void testInDockerContainerNotPrivilegedAlready(final CapturedOutput output) throws Exception {
final Path cgroupPath = Paths.get(copyCgroup("docker-cgroup.txt"));
final MockedStatic<Paths> mocked = createStaticMock(Paths.class);
expectCgroup(mocked, cgroupPath);
assertThat(escalatePrivilegesIfNeeded("foo", "b a r"))
.isEqualTo(ESCALATED);
assertThat(output)
.isEqualTo(resourceContent("expected-escalation-output.txt"));
}
@Test
public void testCustomDockerRegistryOneArg(final CapturedOutput output) throws Exception {
final Path cgroupPath = Paths.get(copyCgroup("docker-cgroup.txt"));
final MockedStatic<Paths> mocked = createStaticMock(Paths.class);
expectCgroup(mocked, cgroupPath);
assertThat(escalatePrivilegesIfNeeded("--docker-registry=my-custom-registry.example.com"))
.isEqualTo(ESCALATED);
assertThat(output.getOut())
.contains("FQ_IMAGE=\"${FORCED_DOCKER_REGISTRY:-my-custom-registry.example.com}/heapdumptool/heapdumptool\"\n");
}
@Test
public void testCustomDockerRegistryTwoArg(final CapturedOutput output) throws Exception {
final Path cgroupPath = Paths.get(copyCgroup("docker-cgroup.txt"));
final MockedStatic<Paths> mocked = createStaticMock(Paths.class);
expectCgroup(mocked, cgroupPath);
assertThat(escalatePrivilegesIfNeeded("--docker-registry", "my-custom-registry.example.com"))
.isEqualTo(ESCALATED);
assertThat(output.getOut())
.contains("FQ_IMAGE=\"${FORCED_DOCKER_REGISTRY:-my-custom-registry.example.com}/heapdumptool/heapdumptool\"\n");
}
@Test
public void testCustomDockerRegistryInvalidArg() throws Exception {
final Path cgroupPath = Paths.get(copyCgroup("docker-cgroup.txt"));
final MockedStatic<Paths> mocked = createStaticMock(Paths.class);
expectCgroup(mocked, cgroupPath);
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> escalatePrivilegesIfNeeded("--docker-registry"))
.withMessage("Cannot find argument value for --docker-registry");
}
@Test
public void testConstructor() throws Exception {
ConstructorTester.test(PrivilegeEscalator.class);
}
private <T> MockedStatic<T> createStaticMock(final Class<T> clazz) {
final MockedStatic<T> mocked = mockStatic(clazz);
closer.register(mocked::close);
return mocked;
}
private void expectNsenter1(final MockedStatic<Paths> mocked, final Path replacement) {
mocked.when(() -> Paths.get("nsenter1"))
.thenReturn(replacement);
}
private void expectCgroup(final MockedStatic<Paths> mocked, final Path replacement) {
mocked.when(() -> Paths.get("/proc/1/cgroup"))
.thenReturn(replacement);
}
private String copyCgroup(final String name) throws IOException {
final Path file = copyResourceToFile(name);
return file.toAbsolutePath().toString();
}
private Path copyResourceToFile(final String name) throws IOException {
final String content = resourceContent(name);
final Path file = tempDir.resolve(name);
Files.write(file, content.getBytes(UTF_8));
return file;
}
private String resourceContent(final String name) throws IOException {
return ResourceTool.contentOf(getClass(), name);
}
}
| 6,356 |
0 | Create_ds/heap-dump-tool/src/test/java/com/paypal/heapdumptool | Create_ds/heap-dump-tool/src/test/java/com/paypal/heapdumptool/capture/CaptureCommandProcessorTest.java | package com.paypal.heapdumptool.capture;
import com.paypal.heapdumptool.fixture.ResourceTool;
import com.paypal.heapdumptool.sanitizer.SanitizeCommandProcessor;
import com.paypal.heapdumptool.utils.ProcessTool;
import com.paypal.heapdumptool.utils.ProcessTool.ProcessResult;
import org.apache.commons.io.input.NullInputStream;
import org.apache.commons.lang3.ArrayUtils;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.MockedStatic;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Instant;
import java.util.stream.Stream;
import static java.time.temporal.ChronoUnit.SECONDS;
import static org.apache.commons.io.output.NullOutputStream.NULL_OUTPUT_STREAM;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.Answers.CALLS_REAL_METHODS;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.mockStatic;
import static org.mockito.Mockito.withSettings;
public class CaptureCommandProcessorTest {
private final Instant now = Instant.parse("2020-09-18T23:33:17.764866Z");
private final Path outputFile = Paths.get("my-app-2020-09-18T23-33-17.764866Z.hprof.zip");
private final MockedStatic<ProcessTool> processToolMock = mockStatic(ProcessTool.class);
private final MockedStatic<Instant> instantMock = mockStatic(Instant.class, withSettings().defaultAnswer(CALLS_REAL_METHODS));
private final MockedStatic<SanitizeCommandProcessor> sanitizerMock = mockStatic(SanitizeCommandProcessor.class);
private final MockedStatic<PrivilegeEscalator> privilegeEscalatorMock = mockStatic(PrivilegeEscalator.class);
@BeforeEach
@AfterEach
public void cleanUpTempFile() throws IOException {
Files.deleteIfExists(outputFile);
}
@AfterEach
public void afterEach() {
Stream.of(processToolMock, instantMock, sanitizerMock, privilegeEscalatorMock)
.forEach(MockedStatic::close);
}
@Test
public void testProcessInContainer() throws Exception {
freezeTime();
expectIsInDockerContainer(true);
expectedProcessInvocations(true);
expectSanitize();
final CaptureCommand command = new CaptureCommand();
command.setContainerName("my-app");
final CaptureCommandProcessor processor = new CaptureCommandProcessor(command);
processor.process();
assertThat(outputFile).exists();
processToolMock.verify(() -> ProcessTool.run("nsenter1", "docker", "ps", "--filter", "name=my-app"));
}
@Test
public void testProcessOnHost() throws Exception {
expectIsInDockerContainer(false);
processToolMock.when(() -> ProcessTool.run("docker", "ps", "--filter", "name=my-app"))
.thenReturn(resultWith("docker-ps-none.txt"));
final CaptureCommand command = new CaptureCommand();
command.setContainerName("my-app");
final CaptureCommandProcessor processor = new CaptureCommandProcessor(command);
assertThatIllegalArgumentException()
.isThrownBy(processor::process)
.withMessageContaining("Cannot find container");
processToolMock.verify(() -> ProcessTool.run("docker", "ps", "--filter", "name=my-app"));
}
private void expectIsInDockerContainer(final boolean value) {
privilegeEscalatorMock.when(PrivilegeEscalator::isInDockerContainer)
.thenReturn(value);
}
private void expectSanitize() throws Exception {
final SanitizeCommandProcessor processor = mock(SanitizeCommandProcessor.class);
doNothing().when(processor).process();
sanitizerMock.when(() -> SanitizeCommandProcessor.newInstance(any(), any()))
.thenAnswer(invocation -> {
final CaptureStreamFactory streamFactory = invocation.getArgument(1, CaptureStreamFactory.class);
streamFactory.newOutputStream(); // create now
return processor;
});
}
private void freezeTime() {
instantMock.when(Instant::now)
.thenReturn(now);
instantMock.when(() -> now.truncatedTo(SECONDS))
.thenReturn(now);
}
private void expectedProcessInvocations(final boolean inContainer) throws IOException {
final CmdFunction cmd = args -> inContainer ? prefixWithNsenter1(args) : args;
processToolMock.when(() -> ProcessTool.run(cmd.maybeWithNsenter1("docker", "ps", "--filter", "name=my-app")))
.thenReturn(resultWith("docker-ps.txt"));
processToolMock.when(() -> ProcessTool.run(cmd.maybeWithNsenter1("docker", "exec", "my-app", "jps")))
.thenReturn(resultWith("docker-exec-jps.txt"));
processToolMock.when(() -> ProcessTool.run(cmd.maybeWithNsenter1("docker", "exec", "my-app", "jcmd", "55", "Thread.print", "-l")))
.thenReturn(resultWith("docker-exec-jcmd-gc-heap-dump.txt"));
final String tmpFile = "/tmp/my-app-2020-09-18T23-33-17.764866Z.hprof";
processToolMock.when(() -> ProcessTool.run(cmd.maybeWithNsenter1("docker", "exec", "my-app", "jcmd", "55", "GC.heap_dump", tmpFile)))
.thenReturn(resultWith("docker-exec-jcmd-gc-heap-dump.txt"));
final ProcessBuilder processBuilder = dockerCpProcess();
processToolMock.when(() -> ProcessTool.processBuilder(cmd.maybeWithNsenter1("docker", "cp", "my-app:" + tmpFile, "-")))
.thenReturn(processBuilder);
}
@FunctionalInterface
private static interface CmdFunction {
String[] maybeWithNsenter1(String... args);
}
private String[] prefixWithNsenter1(final String[] args) {
return ArrayUtils.addFirst(args, "nsenter1");
}
private ProcessBuilder dockerCpProcess() throws IOException {
final ProcessBuilder processBuilder = mock(ProcessBuilder.class);
final Process process = mock(Process.class);
final InputStream nullInputStream = new NullInputStream();
doReturn(process).when(processBuilder).start();
doReturn(nullInputStream).when(process).getInputStream();
doReturn(nullInputStream).when(process).getErrorStream();
doReturn(NULL_OUTPUT_STREAM).when(process).getOutputStream();
return processBuilder;
}
private ProcessResult resultWith(final String stdoutResource) throws IOException {
return new ProcessResult(0, resourceContent(stdoutResource), "");
}
private String resourceContent(final String name) throws IOException {
return ResourceTool.contentOf(getClass(), name);
}
}
| 6,357 |
0 | Create_ds/heap-dump-tool/src/test/java/com/paypal/heapdumptool | Create_ds/heap-dump-tool/src/test/java/com/paypal/heapdumptool/fixture/ResourceTool.java | package com.paypal.heapdumptool.fixture;
import org.apache.commons.io.IOUtils;
import java.io.IOException;
import static java.nio.charset.StandardCharsets.UTF_8;
public class ResourceTool {
public static String contentOf(final Class<?> testClass, final String resourceName) throws IOException {
final String fqPath = getFqPath(testClass, resourceName);
return IOUtils.resourceToString(fqPath, UTF_8);
}
public static byte[] bytesOf(final Class<?> testClass, final String resourceName) throws IOException {
final String fqPath = getFqPath(testClass, resourceName);
return IOUtils.resourceToByteArray(fqPath);
}
private static String getFqPath(final Class<?> testClass, final String resourceName) {
return String.format("/files/%s/%s", testClass.getSimpleName(), resourceName);
}
private ResourceTool() {
throw new AssertionError();
}
}
| 6,358 |
0 | Create_ds/heap-dump-tool/src/test/java/com/paypal/heapdumptool | Create_ds/heap-dump-tool/src/test/java/com/paypal/heapdumptool/fixture/ByteArrayTool.java | package com.paypal.heapdumptool.fixture;
import com.paypal.heapdumptool.sanitizer.DataSize;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
public class ByteArrayTool {
public static int countOfSequence(final byte[] big, final byte[] small) {
int count = 0;
for (int i = 0; i < big.length; i++) {
if (startsWith(big, i, small)) {
count++;
i = i + small.length - 2;
}
}
return count;
}
public static boolean startsWith(final byte[] big, final int bigIndex, final byte[] small) {
int count = 0;
for (int i = bigIndex, j = 0; i < big.length && j < small.length; i++, j++) {
if (big[i] == small[j]) {
count++;
}
}
return count == small.length;
}
public static byte[] lengthen(final byte[] input, final DataSize wantedDataSize) {
return Arrays.copyOf(input, (int) wantedDataSize.toBytes());
}
public static String lengthen(final String input, final DataSize wantedDataSize) {
final byte[] currentBytes = input.getBytes(StandardCharsets.UTF_8);
final byte[] newBytes = lengthen(currentBytes, wantedDataSize);
return new String(newBytes, StandardCharsets.UTF_8);
}
public static byte[] nCopiesLongToBytes(final long value, final int count) {
final ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES * count);
for (int i = 0; i < count; i++) {
buffer.putLong(value);
}
return buffer.array();
}
private ByteArrayTool() {
throw new AssertionError();
}
}
| 6,359 |
0 | Create_ds/heap-dump-tool/src/test/java/com/paypal/heapdumptool | Create_ds/heap-dump-tool/src/test/java/com/paypal/heapdumptool/fixture/MockitoTool.java | package com.paypal.heapdumptool.fixture;
import org.mockito.MockedConstruction;
import org.mockito.stubbing.Answer;
import java.util.concurrent.Callable;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
public class MockitoTool {
/**
* For more conveniently mocking generic parametrized types without eliciting compiler warnings
*/
@SuppressWarnings("unchecked")
public static <T> T genericMock(final Class<?> clazz) {
return (T) mock(clazz);
}
public static <T> Answer<T> voidAnswer() {
return voidAnswer(() -> null);
}
public static <T> Answer<T> voidAnswer(final Callable<?> callable) {
return invocation -> {
callable.call();
return null;
};
}
public static <T> T firstInstance(final MockedConstruction<T> mocked) {
assertThat(mocked.constructed()).hasSizeGreaterThan(1);
return mocked.constructed().get(1);
}
private MockitoTool() {
throw new AssertionError();
}
}
| 6,360 |
0 | Create_ds/heap-dump-tool/src/test/java/com/paypal/heapdumptool | Create_ds/heap-dump-tool/src/test/java/com/paypal/heapdumptool/fixture/ConstructorTester.java | package com.paypal.heapdumptool.fixture;
import java.lang.reflect.Constructor;
import static org.assertj.core.api.Assertions.assertThatCode;
public class ConstructorTester {
public static void test(final Class<?> clazz) throws Exception {
final Constructor<?> constructor = clazz.getDeclaredConstructor();
constructor.setAccessible(true);
assertThatCode(constructor::newInstance).hasRootCauseInstanceOf(AssertionError.class);
}
private ConstructorTester() {
throw new AssertionError();
}
}
| 6,361 |
0 | Create_ds/heap-dump-tool/src/test/java/com/paypal/heapdumptool | Create_ds/heap-dump-tool/src/test/java/com/paypal/heapdumptool/fixture/HeapDumper.java | package com.paypal.heapdumptool.fixture;
import javax.management.MBeanServer;
import java.lang.management.ManagementFactory;
import java.lang.reflect.Method;
import java.nio.file.Path;
public class HeapDumper {
private static final String CLASS_NAME = "com.sun.management.HotSpotDiagnosticMXBean";
private static final String HOTSPOT_BEAN_NAME = "com.sun.management:type=HotSpotDiagnostic";
public static void dumpHeap(final Path path) throws Exception {
dumpHeap(path, false);
}
public static void dumpHeap(final Path path, final boolean live) throws Exception {
final Class<?> clazz = Class.forName(CLASS_NAME);
final Object mxBean = getHotSpotMxBean(clazz);
final Method method = clazz.getMethod("dumpHeap", String.class, boolean.class);
method.invoke(mxBean, path.toString(), live);
}
private static <T> T getHotSpotMxBean(final Class<T> clazz) throws Exception {
final MBeanServer server = ManagementFactory.getPlatformMBeanServer();
return ManagementFactory.newPlatformMXBeanProxy(server, HOTSPOT_BEAN_NAME, clazz);
}
private HeapDumper() {
throw new AssertionError();
}
}
| 6,362 |
0 | Create_ds/heap-dump-tool/src/test/java/com/paypal/heapdumptool | Create_ds/heap-dump-tool/src/test/java/com/paypal/heapdumptool/sanitizer/BasicTypeTest.java | package com.paypal.heapdumptool.sanitizer;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.EnumSource;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
public class BasicTypeTest {
@ParameterizedTest
@EnumSource(BasicType.class)
public void testFindValueSize(final BasicType basicType) {
assertThat(BasicType.findValueSize(basicType.getU1Code(), 8))
.isGreaterThan(0);
}
@Test
public void testUnknownU1Tag() {
assertThatIllegalArgumentException()
.isThrownBy(() -> BasicType.findValueSize(0, 0))
.withMessage("Unknown basic type code: 0");
}
}
| 6,363 |
0 | Create_ds/heap-dump-tool/src/test/java/com/paypal/heapdumptool | Create_ds/heap-dump-tool/src/test/java/com/paypal/heapdumptool/sanitizer/HeapDumpSanitizerTest.java | package com.paypal.heapdumptool.sanitizer;
import com.paypal.heapdumptool.fixture.HeapDumper;
import com.paypal.heapdumptool.fixture.ResourceTool;
import com.paypal.heapdumptool.sanitizer.example.ClassWithManyInstanceFields;
import com.paypal.heapdumptool.sanitizer.example.ClassWithManyStaticFields;
import org.junit.jupiter.api.*;
import org.junit.jupiter.api.MethodOrderer.Random;
import org.junit.jupiter.api.io.TempDir;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors;
import static com.paypal.heapdumptool.ApplicationTestSupport.runApplicationPrivileged;
import static com.paypal.heapdumptool.fixture.ByteArrayTool.*;
import static java.nio.ByteOrder.BIG_ENDIAN;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.Arrays.asList;
import static org.apache.commons.io.FileUtils.byteCountToDisplaySize;
import static org.apache.commons.lang3.ArrayUtils.EMPTY_STRING_ARRAY;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
@TestMethodOrder(Random.class)
public class HeapDumpSanitizerTest {
private static final Logger LOGGER = LoggerFactory.getLogger(HeapDumpSanitizerTest.class);
@TempDir
static Path tempDir;
// "his-secret-value" with each letter incremented by 1
private final String hisSecretValue = "ijt.tfdsfu.wbmvf";
private final String herSecretValue = "ifs.tfdsfu.wbmvf";
private final String itsSecretValue = "jut.tfdsfu.wbmvf";
// "his-classified-value" with each letter incremented by 1
private final String hisClassifiedValue = "ijt.dmbttjgjfe.wbmvf";
private final String herClassifiedValue = "ifs.dmbttjgjfe.wbmvf";
private final String itsClassifiedValue = "jut.dmbttjgjfe.wbmvf";
private final SecretArrays secretArrays = new SecretArrays();
@BeforeEach
public void beforeEach(final TestInfo info) {
LOGGER.info("Test - {}:", info.getDisplayName());
}
@BeforeEach
@AfterEach
public void clearLoadedHeapDumpInfo() {
System.gc();
}
@Test
@DisplayName("testSecretsAreInHeapDump. Verify that heap dump normally contains sensitive data")
public void testSecretsAreInHeapDump() throws Exception {
// keep as byte array in mem
byte[] actualHisSecretValue = adjustLettersToByteArray(hisSecretValue);
// keep as char array in mem
String actualHerSecretValue = new String(actualHisSecretValue, UTF_8).replace("his", "her");
// interned
lengthenAndInternItsValue(actualHisSecretValue);
actualHisSecretValue = lengthen(actualHisSecretValue, DataSize.ofMegabytes(1));
actualHerSecretValue = lengthen(actualHerSecretValue, DataSize.ofMegabytes(1));
final byte[] heapDump = loadHeapDump();
final byte[] expectedHisSecretValueBytes = adjustLettersToByteArray(hisSecretValue);
final byte[] expectedHerSecretValueBytes = adjustLettersToByteArray(herSecretValue);
final byte[] expectedItsSecretValueBytes = adjustLettersToByteArray(itsSecretValue);
assertThat(heapDump)
.overridingErrorMessage("sequences do not match") // normal error message would be long and not helpful at all
.containsSequence(expectedHisSecretValueBytes)
.containsSequence(expectedHerSecretValueBytes)
.containsSequence(expectedItsSecretValueBytes)
.containsSequence(secretArrays.getByteArraySequence())
.containsSequence(secretArrays.getCharArraySequence())
.containsSequence(secretArrays.getShortArraySequence())
.containsSequence(secretArrays.getIntArraySequence())
.containsSequence(secretArrays.getLongArraySequence())
.containsSequence(secretArrays.getFloatArraySequence())
.containsSequence(secretArrays.getDoubleArraySequence())
.containsSequence(secretArrays.getBooleanArraySequence());
}
@Test
@DisplayName("testConfidentialsNotInHeapDump. Verify that sanitized heap dump does not contains sensitive data")
public void testConfidentialsNotInHeapDump() throws Exception {
byte[] actualHisConfidentialValue = ResourceTool.bytesOf(getClass(), "classifieds.txt");
String actualHerConfidentialValue = new String(actualHisConfidentialValue, UTF_8).replace("his", "her");
lengthenAndInternItsValue(actualHisConfidentialValue);
actualHisConfidentialValue = lengthen(actualHisConfidentialValue, DataSize.ofMegabytes(1));
actualHerConfidentialValue = lengthen(actualHerConfidentialValue, DataSize.ofMegabytes(1));
final byte[] heapDump = loadSanitizedHeapDump();
final byte[] expectedHisClassifiedValueBytes = adjustLettersToByteArray(hisClassifiedValue);
final byte[] expectedHerClassifiedValueBytes = adjustLettersToByteArray(herClassifiedValue);
final byte[] expectedItsClassifiedValueBytes = adjustLettersToByteArray(itsClassifiedValue);
verifyDoesNotContainsSequence(heapDump, expectedHisClassifiedValueBytes);
verifyDoesNotContainsSequence(heapDump, expectedHerClassifiedValueBytes);
verifyDoesNotContainsSequence(heapDump, expectedItsClassifiedValueBytes);
verifyDoesNotContainsSequence(heapDump, secretArrays.getByteArraySequence());
verifyDoesNotContainsSequence(heapDump, secretArrays.getCharArraySequence());
// by default only byte and char arrays are sanitized
assertThat(heapDump)
.overridingErrorMessage("sequences do not match") // normal error message would be long and not helpful at all
.containsSequence(secretArrays.getShortArraySequence())
.containsSequence(secretArrays.getIntArraySequence())
.containsSequence(secretArrays.getLongArraySequence())
.containsSequence(secretArrays.getFloatArraySequence())
.containsSequence(secretArrays.getDoubleArraySequence())
.containsSequence(secretArrays.getBooleanArraySequence());
}
@Test
@DisplayName("testSanitizeFieldsOfNonArrayPrimitiveType. Verify that fields of non-array primitive type can be sanitized")
public void testSanitizeFieldsOfNonArrayPrimitiveType() throws Exception {
final Object instance = new ClassWithManyInstanceFields();
final Object staticFields = new ClassWithManyStaticFields();
assertThat(instance).isNotNull();
assertThat(staticFields).isNotNull();
byte[] sanitizedHeapDump = loadSanitizedHeapDump("--sanitize-byte-char-arrays-only=false");
verifyDoesNotContainsSequence(sanitizedHeapDump, nCopiesLongToBytes(deadcow(), 100));
assertThat(countOfSequence(sanitizedHeapDump, nCopiesLongToBytes(cafegirl(), 1)))
.isLessThan(1000);
sanitizedHeapDump = null;
clearLoadedHeapDumpInfo();
{
final byte[] clearHeapDump = loadSanitizedHeapDump("--sanitize-byte-char-arrays-only=true");
assertThat(clearHeapDump)
.overridingErrorMessage("sequences do not match") // normal error message would be long and not helpful at all
.containsSequence(nCopiesLongToBytes(deadcow(), 500));
assertThat(countOfSequence(clearHeapDump, nCopiesLongToBytes(cafegirl(), 1)))
.isGreaterThan(500);
}
{
final byte[] clearHeapDump = loadSanitizedHeapDump("--sanitize-byte-char-arrays-only=false", "--sanitize-arrays-only=true");
assertThat(clearHeapDump)
.overridingErrorMessage("sequences do not match") // normal error message would be long and not helpful at all
.containsSequence(nCopiesLongToBytes(deadcow(), 500));
assertThat(countOfSequence(clearHeapDump, nCopiesLongToBytes(cafegirl(), 1)))
.isGreaterThan(500);
}
}
@Test
public void testSanitizeArraysOnly() throws Exception {
final byte[] heapDump = loadSanitizedHeapDump("--sanitize-byte-char-arrays-only=false", "--sanitize-arrays-only=true");
verifyDoesNotContainsSequence(heapDump, secretArrays.getByteArraySequence());
verifyDoesNotContainsSequence(heapDump, secretArrays.getCharArraySequence());
verifyDoesNotContainsSequence(heapDump, secretArrays.getShortArraySequence());
verifyDoesNotContainsSequence(heapDump, secretArrays.getIntArraySequence());
verifyDoesNotContainsSequence(heapDump, secretArrays.getLongArraySequence());
verifyDoesNotContainsSequence(heapDump, secretArrays.getFloatArraySequence());
verifyDoesNotContainsSequence(heapDump, secretArrays.getDoubleArraySequence());
verifyDoesNotContainsSequence(heapDump, secretArrays.getBooleanArraySequence());
}
// 0xDEADBEEF
private long deadcow() {
return 0xDEADBEEE + Long.parseLong("1");
}
// 0xCAFEBABE
private long cafegirl() {
return 0XCAFEBABD + Long.parseLong("1");
}
private void verifyDoesNotContainsSequence(final byte[] big, final byte[] small) {
final String corrId = System.currentTimeMillis() + "";
assertThatCode(() -> {
assertThat(big)
.withFailMessage(corrId).containsSequence(small);
}).withFailMessage("does in fact contains sequence")
.hasMessageContaining(corrId);
}
private void lengthenAndInternItsValue(final byte[] value) {
String itsValue = new String(value, UTF_8).replace("his", "its");
itsValue = lengthen(itsValue, DataSize.ofMegabytes(1));
itsValue.intern();
}
private byte[] adjustLettersToByteArray(final String str) {
return adjustLetters(str, -1)
.getBytes(UTF_8);
}
private String adjustLetters(final String str, final int adjustment) {
return str.chars()
.map(chr -> chr + adjustment)
.mapToObj(chr -> String.valueOf((char) chr))
.collect(Collectors.joining(""));
}
private Path triggerHeapDump() throws Exception {
final Path heapDumpPath = newTempFilePath();
LOGGER.info("Heap dumping to {}", heapDumpPath);
HeapDumper.dumpHeap(heapDumpPath);
return heapDumpPath;
}
private byte[] loadHeapDump() throws Exception {
return loadHeapDump(triggerHeapDump());
}
private byte[] loadHeapDump(final Path heapDumpPath) throws IOException {
final long size = Files.size(heapDumpPath);
LOGGER.info("Loading heap dump. size={} name={}", byteCountToDisplaySize(size), heapDumpPath.getFileName());
return Files.readAllBytes(heapDumpPath);
}
private byte[] loadSanitizedHeapDump(final String... options) throws Exception {
final Path heapDump = triggerHeapDump();
final Path sanitizedHeapDumpPath = newTempFilePath();
final List<String> cmd = new ArrayList<>();
cmd.add("sanitize");
cmd.addAll(asList(options));
cmd.add(heapDump.toString());
cmd.add(sanitizedHeapDumpPath.toString());
runApplicationPrivileged(cmd.toArray(EMPTY_STRING_ARRAY));
return loadHeapDump(sanitizedHeapDumpPath);
}
private Path newTempFilePath() throws IOException {
final Path path = Files.createTempFile(tempDir, getClass().getSimpleName(), ".hprof");
Files.delete(path);
return path;
}
private static class SecretArrays {
private static final int LENGTH = 512;
private final byte[] byteArray = new byte[LENGTH];
private final char[] charArray = new char[LENGTH];
private final short[] shortArray = new short[LENGTH];
private final int[] intArray = new int[LENGTH];
private final long[] longArray = new long[LENGTH];
private final float[] floatArray = new float[LENGTH];
private final double[] doubleArray = new double[LENGTH];
private final boolean[] booleanArray = new boolean[LENGTH];
{
final ThreadLocalRandom random = ThreadLocalRandom.current();
for (int i = 0; i < LENGTH; i++) {
byteArray[i] = (byte) random.nextInt();
charArray[i] = (char) random.nextInt();
shortArray[i] = (short) random.nextInt();
intArray[i] = random.nextInt();
longArray[i] = random.nextLong();
floatArray[i] = random.nextFloat();
doubleArray[i] = random.nextDouble();
booleanArray[i] = random.nextBoolean();
}
}
public byte[] getByteArraySequence() {
return byteArray;
}
public byte[] getCharArraySequence() {
final ByteBuffer buffer = ByteBuffer.allocate(Character.BYTES * LENGTH);
buffer.order(BIG_ENDIAN);
for (int i = 0; i < LENGTH; i++) {
buffer.putChar(i * Character.BYTES, charArray[i]);
}
return buffer.array();
}
public byte[] getShortArraySequence() {
final ByteBuffer buffer = ByteBuffer.allocate(Short.BYTES * LENGTH);
buffer.order(BIG_ENDIAN);
for (int i = 0; i < LENGTH; i++) {
buffer.putShort(i * Short.BYTES, shortArray[i]);
}
return buffer.array();
}
public byte[] getIntArraySequence() {
final ByteBuffer buffer = ByteBuffer.allocate(Integer.BYTES * LENGTH);
buffer.order(BIG_ENDIAN);
for (int i = 0; i < LENGTH; i++) {
buffer.putInt(i * Integer.BYTES, intArray[i]);
}
return buffer.array();
}
public byte[] getLongArraySequence() {
final ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES * LENGTH);
buffer.order(BIG_ENDIAN);
for (int i = 0; i < LENGTH; i++) {
buffer.putLong(i * Long.BYTES, longArray[i]);
}
return buffer.array();
}
public byte[] getFloatArraySequence() {
final ByteBuffer buffer = ByteBuffer.allocate(Float.BYTES * LENGTH);
buffer.order(BIG_ENDIAN);
for (int i = 0; i < LENGTH; i++) {
buffer.putFloat(i * Float.BYTES, floatArray[i]);
}
return buffer.array();
}
public byte[] getDoubleArraySequence() {
final ByteBuffer buffer = ByteBuffer.allocate(Double.BYTES * LENGTH);
buffer.order(BIG_ENDIAN);
for (int i = 0; i < LENGTH; i++) {
buffer.putDouble(i * Double.BYTES, doubleArray[i]);
}
return buffer.array();
}
public byte[] getBooleanArraySequence() {
final ByteBuffer buffer = ByteBuffer.allocate(LENGTH);
buffer.order(BIG_ENDIAN);
for (int i = 0; i < LENGTH; i++) {
buffer.put(i, booleanArray[i] ? (byte) 1 : (byte) 0);
}
return buffer.array();
}
}
}
| 6,364 |
0 | Create_ds/heap-dump-tool/src/test/java/com/paypal/heapdumptool | Create_ds/heap-dump-tool/src/test/java/com/paypal/heapdumptool/sanitizer/SanitizeCommandProcessorTest.java | package com.paypal.heapdumptool.sanitizer;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.MockedConstruction;
import java.io.IOException;
import java.nio.file.Paths;
import static com.paypal.heapdumptool.fixture.MockitoTool.firstInstance;
import static com.paypal.heapdumptool.sanitizer.DataSize.ofBytes;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.mockConstruction;
import static org.mockito.Mockito.verify;
public class SanitizeCommandProcessorTest {
private final HeapDumpSanitizer sanitizer = mock(HeapDumpSanitizer.class);
private final SanitizeStreamFactory streamFactory = mock(SanitizeStreamFactory.class);
private final SanitizeCommand command = new SanitizeCommand();
@BeforeEach
public void beforeEach() throws IOException {
doNothing().when(sanitizer).sanitize();
doReturn(null).when(streamFactory).newInputStream();
doReturn(null).when(streamFactory).newOutputStream();
command.setInputFile(Paths.get("input"));
command.setOutputFile(Paths.get("output"));
}
@Test
public void testBufferSizeValidation() {
command.setBufferSize(ofBytes(-1));
assertThatThrownBy(() -> new SanitizeCommandProcessor(command))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Invalid buffer size");
}
@Test
public void testProcess() throws Exception {
final SanitizeCommandProcessor processor = new SanitizeCommandProcessor(command, streamFactory);
try (final MockedConstruction<HeapDumpSanitizer> mocked = mockConstruction(HeapDumpSanitizer.class)) {
final HeapDumpSanitizer sanitizer = new HeapDumpSanitizer();
doNothing().when(sanitizer).sanitize();
processor.process();
verify(firstInstance(mocked)).sanitize();
}
}
}
| 6,365 |
0 | Create_ds/heap-dump-tool/src/test/java/com/paypal/heapdumptool | Create_ds/heap-dump-tool/src/test/java/com/paypal/heapdumptool/sanitizer/PipeTest.java | package com.paypal.heapdumptool.sanitizer;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicLong;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class PipeTest {
private final String data = "hello world\0more-stuff-here";
private final ByteArrayInputStream inputBytes = byteStreamOf(data);
private final ByteArrayOutputStream outputBytes = new ByteArrayOutputStream();
private final AtomicLong monitor = new AtomicLong();
private final Pipe pipe = new Pipe(inputBytes, outputBytes, monitor::set);
@Test
public void testIdSizeSetGet() {
pipe.setIdSize(4);
assertThat(pipe.getIdSize())
.isEqualTo(4);
pipe.setIdSize(8);
assertThat(pipe.getIdSize())
.isEqualTo(8);
}
@Test
@DisplayName("testIdSizeNullDefault. check that NPE is thrown")
public void testIdSizeNullDefault() {
assertThatThrownBy(pipe::getIdSize)
.isInstanceOf(NullPointerException.class);
}
@Test
public void testIdSize4Or8() {
assertThatThrownBy(() -> pipe.setIdSize(10))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Unknown id size: 10");
}
@Test
public void testReadU1() throws IOException {
assertThat(pipe.readU1())
.isEqualTo('h');
pipe.skipInput(data.length() - 1);
verifyEoF();
assertThat(outputBytes.toByteArray())
.hasSize(0);
}
@Test
public void testWriteU1() throws IOException {
pipe.writeU1('z');
assertThat(outputString())
.isEqualTo("z");
verifyInputStreamUnchanged();
}
@Test
public void testPipeByLength() throws IOException {
pipe.pipe(data.length());
verifyEoF();
assertThat(outputString())
.isEqualTo(data);
}
@Test
public void testPipeId4() throws IOException {
pipe.setIdSize(4);
pipe.pipeId();
assertThat(outputString())
.isEqualTo("hell")
.hasSize(4);
}
@Test
public void testPipeId8() throws IOException {
pipe.setIdSize(8);
pipe.pipeId();
assertThat(outputString())
.isEqualTo("hello wo")
.hasSize(8);
}
@Test
public void testCopyFrom() throws IOException {
final String newData = "byte stream data";
pipe.copyFrom(byteStreamOf(newData), newData.length());
verifyInputStreamUnchanged();
assertThat(outputString())
.isEqualTo(newData);
}
@Test
public void testPipeU1() throws IOException {
final int u1 = pipe.pipeU1();
assertThat(u1)
.isEqualTo('h');
assertThat(outputString())
.isEqualTo("h");
assertThat(inputBytes.read())
.isEqualTo('e');
}
@Test
public void testPipeU1IfPossible() throws IOException {
final int u1 = pipe.pipeU1IfPossible();
assertThat(u1)
.isEqualTo('h');
assertThat(outputString())
.isEqualTo("h");
assertThat(inputBytes.read())
.isEqualTo('e');
}
@Test
@DisplayName("pipe u1 on exhausted input")
public void testPipeU1IfPossibleNot() throws IOException {
pipe.pipe(100);
final int u1 = pipe.pipeU1IfPossible();
assertThat(u1)
.isEqualTo(-1);
assertThat(outputString())
.isEqualTo(data);
}
@Test
public void testPipeU2() throws IOException {
pipe.pipeU2();
assertThat(inputBytes.read())
.isEqualTo('l');
assertThat(outputString())
.isEqualTo("he");
}
@Test
public void testPipeNullTerminatedString() throws IOException {
assertThat(pipe.pipeNullTerminatedString())
.isEqualTo("hello world\0")
.isEqualTo(outputString());
}
@Test
public void testNewInputBoundedPipe() throws IOException {
pipe.pipeU1();
final Pipe boundedPipe = pipe.newInputBoundedPipe(4);
assertThat(boundedPipe.pipeNullTerminatedString())
.isEqualTo("ello");
assertThat(outputString())
.isEqualTo("hello");
assertThat(pipe.pipeNullTerminatedString())
.isEqualTo(" world\0");
assertThat(outputString())
.isEqualTo("hello world\0");
}
@Test
public void testProgressMonitor() throws IOException {
pipe.pipeU1();
assertThat(monitor)
.hasValue(1);
pipe.pipe(100);
assertThat(monitor)
.hasValue(data.length());
}
private void verifyEoF() throws IOException {
assertThat(pipe.readU1())
.isEqualTo(-1);
}
private void verifyInputStreamUnchanged() {
assertThat(inputBytes.read())
.isEqualTo('h');
}
private String outputString() throws IOException {
return outputBytes.toString("UTF-8");
}
private ByteArrayInputStream byteStreamOf(final String str) {
return new ByteArrayInputStream(bytesOf(str));
}
private byte[] bytesOf(final String str) {
return str.getBytes(UTF_8);
}
}
| 6,366 |
0 | Create_ds/heap-dump-tool/src/test/java/com/paypal/heapdumptool | Create_ds/heap-dump-tool/src/test/java/com/paypal/heapdumptool/sanitizer/DataSizeTests.java | /*
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.paypal.heapdumptool.sanitizer;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Tests for {@link DataSize}.
*
* @author Stephane Nicoll
*/
public class DataSizeTests {
@Test
void ofBytesToBytes() {
assertThat(DataSize.ofBytes(1024).toBytes()).isEqualTo(1024);
}
@Test
void ofBytesToKilobytes() {
assertThat(DataSize.ofBytes(1024).toKilobytes()).isEqualTo(1);
}
@Test
void ofKilobytesToKilobytes() {
assertThat(DataSize.ofKilobytes(1024).toKilobytes()).isEqualTo(1024);
}
@Test
void ofKilobytesToMegabytes() {
assertThat(DataSize.ofKilobytes(1024).toMegabytes()).isEqualTo(1);
}
@Test
void ofMegabytesToMegabytes() {
assertThat(DataSize.ofMegabytes(1024).toMegabytes()).isEqualTo(1024);
}
@Test
void ofMegabytesToGigabytes() {
assertThat(DataSize.ofMegabytes(2048).toGigabytes()).isEqualTo(2);
}
@Test
void ofGigabytesToGigabytes() {
assertThat(DataSize.ofGigabytes(4096).toGigabytes()).isEqualTo(4096);
}
@Test
void ofGigabytesToTerabytes() {
assertThat(DataSize.ofGigabytes(4096).toTerabytes()).isEqualTo(4);
}
@Test
void ofTerabytesToGigabytes() {
assertThat(DataSize.ofTerabytes(1).toGigabytes()).isEqualTo(1024);
}
@Test
void ofWithBytesUnit() {
assertThat(DataSize.of(10, DataUnit.BYTES)).isEqualTo(DataSize.ofBytes(10));
}
@Test
void ofWithKilobytesUnit() {
assertThat(DataSize.of(20, DataUnit.KILOBYTES)).isEqualTo(DataSize.ofKilobytes(20));
}
@Test
void ofWithMegabytesUnit() {
assertThat(DataSize.of(30, DataUnit.MEGABYTES)).isEqualTo(DataSize.ofMegabytes(30));
}
@Test
void ofWithGigabytesUnit() {
assertThat(DataSize.of(40, DataUnit.GIGABYTES)).isEqualTo(DataSize.ofGigabytes(40));
}
@Test
void ofWithTerabytesUnit() {
assertThat(DataSize.of(50, DataUnit.TERABYTES)).isEqualTo(DataSize.ofTerabytes(50));
}
@Test
void parseWithDefaultUnitUsesBytes() {
assertThat(DataSize.parse("1024")).isEqualTo(DataSize.ofKilobytes(1));
}
@Test
void parseNegativeNumberWithDefaultUnitUsesBytes() {
assertThat(DataSize.parse("-1")).isEqualTo(DataSize.ofBytes(-1));
}
@Test
void parseWithNullDefaultUnitUsesBytes() {
assertThat(DataSize.parse("1024", null)).isEqualTo(DataSize.ofKilobytes(1));
}
@Test
void parseNegativeNumberWithNullDefaultUnitUsesBytes() {
assertThat(DataSize.parse("-1024", null)).isEqualTo(DataSize.ofKilobytes(-1));
}
@Test
void parseWithCustomDefaultUnit() {
assertThat(DataSize.parse("1", DataUnit.KILOBYTES)).isEqualTo(DataSize.ofKilobytes(1));
}
@Test
void parseNegativeNumberWithCustomDefaultUnit() {
assertThat(DataSize.parse("-1", DataUnit.KILOBYTES)).isEqualTo(DataSize.ofKilobytes(-1));
}
@Test
void parseWithBytes() {
assertThat(DataSize.parse("1024B")).isEqualTo(DataSize.ofKilobytes(1));
}
@Test
void parseWithNegativeBytes() {
assertThat(DataSize.parse("-1024B")).isEqualTo(DataSize.ofKilobytes(-1));
}
@Test
void parseWithPositiveBytes() {
assertThat(DataSize.parse("+1024B")).isEqualTo(DataSize.ofKilobytes(1));
}
@Test
void parseWithKilobytes() {
assertThat(DataSize.parse("1KB")).isEqualTo(DataSize.ofBytes(1024));
}
@Test
void parseWithNegativeKilobytes() {
assertThat(DataSize.parse("-1KB")).isEqualTo(DataSize.ofBytes(-1024));
}
@Test
void parseWithMegabytes() {
assertThat(DataSize.parse("4MB")).isEqualTo(DataSize.ofMegabytes(4));
}
@Test
void parseWithNegativeMegabytes() {
assertThat(DataSize.parse("-4MB")).isEqualTo(DataSize.ofMegabytes(-4));
}
@Test
void parseWithGigabytes() {
assertThat(DataSize.parse("1GB")).isEqualTo(DataSize.ofMegabytes(1024));
}
@Test
void parseWithNegativeGigabytes() {
assertThat(DataSize.parse("-1GB")).isEqualTo(DataSize.ofMegabytes(-1024));
}
@Test
void parseWithTerabytes() {
assertThat(DataSize.parse("1TB")).isEqualTo(DataSize.ofTerabytes(1));
}
@Test
void parseWithNegativeTerabytes() {
assertThat(DataSize.parse("-1TB")).isEqualTo(DataSize.ofTerabytes(-1));
}
@Test
void isNegativeWithPositive() {
assertThat(DataSize.ofBytes(50).isNegative()).isFalse();
}
@Test
void isNegativeWithZero() {
assertThat(DataSize.ofBytes(0).isNegative()).isFalse();
}
@Test
void isNegativeWithNegative() {
assertThat(DataSize.ofBytes(-1).isNegative()).isTrue();
}
@Test
void toStringUsesBytes() {
assertThat(DataSize.ofKilobytes(1).toString()).isEqualTo("1024B");
}
@Test
void toStringWithNegativeBytes() {
assertThat(DataSize.ofKilobytes(-1).toString()).isEqualTo("-1024B");
}
@Test
void parseWithUnsupportedUnit() {
assertThatIllegalArgumentException().isThrownBy(() -> DataSize.parse("3WB"))
.withMessage("'3WB' is not a valid data size");
}
}
| 6,367 |
0 | Create_ds/heap-dump-tool/src/test/java/com/paypal/heapdumptool | Create_ds/heap-dump-tool/src/test/java/com/paypal/heapdumptool/sanitizer/SanitizeStreamFactoryTest.java | package com.paypal.heapdumptool.sanitizer;
import com.paypal.heapdumptool.fixture.ResourceTool;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.zip.ZipOutputStream;
import static com.paypal.heapdumptool.sanitizer.DataSize.ofBytes;
import static java.nio.file.StandardOpenOption.TRUNCATE_EXISTING;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
public class SanitizeStreamFactoryTest {
@TempDir
Path tempDir;
private SanitizeStreamFactory streamFactory;
@Test
public void testStdinInputStream() throws IOException {
final SanitizeCommand cmd = newCommand();
cmd.setInputFile(Paths.get("-"));
cmd.setBufferSize(ofBytes(0));
streamFactory = new SanitizeStreamFactory(cmd);
assertThat(streamFactory.newInputStream())
.isEqualTo(System.in);
}
@Test
public void testBufferedInputStream() throws IOException {
final SanitizeCommand cmd = newCommand();
cmd.setInputFile(Paths.get("-"));
streamFactory = new SanitizeStreamFactory(cmd);
assertThat(streamFactory.newInputStream())
.isInstanceOf(BufferedInputStream.class)
.isNotSameAs(System.in);
}
@Test
public void testBufferedOutputStream() throws IOException {
final SanitizeCommand cmd = newCommand();
cmd.setOutputFile(tempDir.resolve("testBufferedOutputStream"));
streamFactory = new SanitizeStreamFactory(cmd);
assertThat(streamFactory.newOutputStream())
.isInstanceOf(BufferedOutputStream.class);
}
@Test
public void testFileInputStream() throws IOException {
final Path inputFile = Files.createTempFile(tempDir, getClass().getSimpleName(), ".hprof");
final SanitizeCommand cmd = newCommand();
cmd.setInputFile(inputFile);
cmd.setBufferSize(ofBytes(0));
streamFactory = new SanitizeStreamFactory(cmd);
assertThat(streamFactory.newInputStream())
.isNotInstanceOf(PrintStream.class);
}
@Test
public void testFileOutputStream() throws IOException {
final Path file = Files.createTempFile(tempDir, getClass().getSimpleName(), ".hprof");
final SanitizeCommand cmd = newCommand();
cmd.setInputFile(Paths.get("foo"));
cmd.setOutputFile(file);
cmd.setBufferSize(ofBytes(0));
streamFactory = new SanitizeStreamFactory(cmd);
assertThat(streamFactory.newOutputStream())
.isNotInstanceOf(PrintStream.class);
}
@Test
public void testTarInputStream() throws IOException {
final Path inputFile = Files.createTempFile(tempDir, getClass().getSimpleName(), ".hprof");
writeTar(inputFile);
final SanitizeCommand cmd = newCommand();
cmd.setInputFile(inputFile);
cmd.setBufferSize(ofBytes(0));
cmd.setTarInput(true);
streamFactory = new SanitizeStreamFactory(cmd);
assertThat(streamFactory.newInputStream())
.isInstanceOf(TarArchiveInputStream.class);
}
@Test
public void testZipOutputStream() throws IOException {
final Path outputFile = Files.createTempFile(tempDir, getClass().getSimpleName(), ".zip");
final SanitizeCommand cmd = newCommand();
cmd.setInputFile(Paths.get("foo"));
cmd.setOutputFile(outputFile);
cmd.setBufferSize(ofBytes(0));
cmd.setZipOutput(true);
streamFactory = new SanitizeStreamFactory(cmd);
assertThat(streamFactory.newOutputStream())
.isInstanceOf(ZipOutputStream.class);
}
@Test
public void testSameInputOutput() {
final SanitizeCommand cmd = newCommand();
cmd.setInputFile(Paths.get("foo"));
cmd.setOutputFile(Paths.get("foo"));
assertThatIllegalArgumentException()
.isThrownBy(() -> new SanitizeStreamFactory(cmd));
}
private void writeTar(final Path destPath) throws IOException {
final byte[] srcBytes = ResourceTool.bytesOf(getClass(), "sample.tar");
Files.write(destPath, srcBytes, TRUNCATE_EXISTING);
}
private SanitizeCommand newCommand() {
final SanitizeCommand cmd = new SanitizeCommand();
cmd.setInputFile(Paths.get("input.txt"));
cmd.setOutputFile(Paths.get("output.txt"));
return cmd;
}
}
| 6,368 |
0 | Create_ds/heap-dump-tool/src/test/java/com/paypal/heapdumptool | Create_ds/heap-dump-tool/src/test/java/com/paypal/heapdumptool/sanitizer/SanitizeCommandTest.java | package com.paypal.heapdumptool.sanitizer;
import org.junit.jupiter.api.Test;
import org.meanbean.test.BeanVerifier;
import static com.paypal.heapdumptool.sanitizer.DataSize.ofMegabytes;
import static org.assertj.core.api.Assertions.assertThat;
public class SanitizeCommandTest {
@Test
public void testBean() {
BeanVerifier.forClass(SanitizeCommand.class)
.withSettings(settings -> settings.addOverridePropertyFactory(SanitizeCommand::getBufferSize, () -> ofMegabytes(5)))
.verifyGettersAndSetters();
}
@Test
public void testSanitizationText() {
assertThat(escapedSanitizationText("\\0"))
.isEqualTo("\0");
assertThat(escapedSanitizationText("\0"))
.isEqualTo("\0");
assertThat(escapedSanitizationText("foobar"))
.isEqualTo("foobar");
}
private String escapedSanitizationText(final String sanitizationText) {
final SanitizeCommand cmd = new SanitizeCommand();
cmd.setSanitizationText(sanitizationText);
return cmd.getSanitizationText();
}
}
| 6,369 |
0 | Create_ds/heap-dump-tool/src/test/java/com/paypal/heapdumptool/sanitizer | Create_ds/heap-dump-tool/src/test/java/com/paypal/heapdumptool/sanitizer/example/ClassWithManyStaticFields.java | package com.paypal.heapdumptool.sanitizer.example;
public class ClassWithManyStaticFields {
public static long l0 = 0xCAFEBABE;
public static long l1 = 0xCAFEBABE;
public static long l2 = 0xCAFEBABE;
public static long l3 = 0xCAFEBABE;
public static long l4 = 0xCAFEBABE;
public static long l5 = 0xCAFEBABE;
public static long l6 = 0xCAFEBABE;
public static long l7 = 0xCAFEBABE;
public static long l8 = 0xCAFEBABE;
public static long l9 = 0xCAFEBABE;
public static long l10 = 0xCAFEBABE;
public static long l11 = 0xCAFEBABE;
public static long l12 = 0xCAFEBABE;
public static long l13 = 0xCAFEBABE;
public static long l14 = 0xCAFEBABE;
public static long l15 = 0xCAFEBABE;
public static long l16 = 0xCAFEBABE;
public static long l17 = 0xCAFEBABE;
public static long l18 = 0xCAFEBABE;
public static long l19 = 0xCAFEBABE;
public static long l20 = 0xCAFEBABE;
public static long l21 = 0xCAFEBABE;
public static long l22 = 0xCAFEBABE;
public static long l23 = 0xCAFEBABE;
public static long l24 = 0xCAFEBABE;
public static long l25 = 0xCAFEBABE;
public static long l26 = 0xCAFEBABE;
public static long l27 = 0xCAFEBABE;
public static long l28 = 0xCAFEBABE;
public static long l29 = 0xCAFEBABE;
public static long l30 = 0xCAFEBABE;
public static long l31 = 0xCAFEBABE;
public static long l32 = 0xCAFEBABE;
public static long l33 = 0xCAFEBABE;
public static long l34 = 0xCAFEBABE;
public static long l35 = 0xCAFEBABE;
public static long l36 = 0xCAFEBABE;
public static long l37 = 0xCAFEBABE;
public static long l38 = 0xCAFEBABE;
public static long l39 = 0xCAFEBABE;
public static long l40 = 0xCAFEBABE;
public static long l41 = 0xCAFEBABE;
public static long l42 = 0xCAFEBABE;
public static long l43 = 0xCAFEBABE;
public static long l44 = 0xCAFEBABE;
public static long l45 = 0xCAFEBABE;
public static long l46 = 0xCAFEBABE;
public static long l47 = 0xCAFEBABE;
public static long l48 = 0xCAFEBABE;
public static long l49 = 0xCAFEBABE;
public static long l50 = 0xCAFEBABE;
public static long l51 = 0xCAFEBABE;
public static long l52 = 0xCAFEBABE;
public static long l53 = 0xCAFEBABE;
public static long l54 = 0xCAFEBABE;
public static long l55 = 0xCAFEBABE;
public static long l56 = 0xCAFEBABE;
public static long l57 = 0xCAFEBABE;
public static long l58 = 0xCAFEBABE;
public static long l59 = 0xCAFEBABE;
public static long l60 = 0xCAFEBABE;
public static long l61 = 0xCAFEBABE;
public static long l62 = 0xCAFEBABE;
public static long l63 = 0xCAFEBABE;
public static long l64 = 0xCAFEBABE;
public static long l65 = 0xCAFEBABE;
public static long l66 = 0xCAFEBABE;
public static long l67 = 0xCAFEBABE;
public static long l68 = 0xCAFEBABE;
public static long l69 = 0xCAFEBABE;
public static long l70 = 0xCAFEBABE;
public static long l71 = 0xCAFEBABE;
public static long l72 = 0xCAFEBABE;
public static long l73 = 0xCAFEBABE;
public static long l74 = 0xCAFEBABE;
public static long l75 = 0xCAFEBABE;
public static long l76 = 0xCAFEBABE;
public static long l77 = 0xCAFEBABE;
public static long l78 = 0xCAFEBABE;
public static long l79 = 0xCAFEBABE;
public static long l80 = 0xCAFEBABE;
public static long l81 = 0xCAFEBABE;
public static long l82 = 0xCAFEBABE;
public static long l83 = 0xCAFEBABE;
public static long l84 = 0xCAFEBABE;
public static long l85 = 0xCAFEBABE;
public static long l86 = 0xCAFEBABE;
public static long l87 = 0xCAFEBABE;
public static long l88 = 0xCAFEBABE;
public static long l89 = 0xCAFEBABE;
public static long l90 = 0xCAFEBABE;
public static long l91 = 0xCAFEBABE;
public static long l92 = 0xCAFEBABE;
public static long l93 = 0xCAFEBABE;
public static long l94 = 0xCAFEBABE;
public static long l95 = 0xCAFEBABE;
public static long l96 = 0xCAFEBABE;
public static long l97 = 0xCAFEBABE;
public static long l98 = 0xCAFEBABE;
public static long l99 = 0xCAFEBABE;
public static long l100 = 0xCAFEBABE;
public static long l101 = 0xCAFEBABE;
public static long l102 = 0xCAFEBABE;
public static long l103 = 0xCAFEBABE;
public static long l104 = 0xCAFEBABE;
public static long l105 = 0xCAFEBABE;
public static long l106 = 0xCAFEBABE;
public static long l107 = 0xCAFEBABE;
public static long l108 = 0xCAFEBABE;
public static long l109 = 0xCAFEBABE;
public static long l110 = 0xCAFEBABE;
public static long l111 = 0xCAFEBABE;
public static long l112 = 0xCAFEBABE;
public static long l113 = 0xCAFEBABE;
public static long l114 = 0xCAFEBABE;
public static long l115 = 0xCAFEBABE;
public static long l116 = 0xCAFEBABE;
public static long l117 = 0xCAFEBABE;
public static long l118 = 0xCAFEBABE;
public static long l119 = 0xCAFEBABE;
public static long l120 = 0xCAFEBABE;
public static long l121 = 0xCAFEBABE;
public static long l122 = 0xCAFEBABE;
public static long l123 = 0xCAFEBABE;
public static long l124 = 0xCAFEBABE;
public static long l125 = 0xCAFEBABE;
public static long l126 = 0xCAFEBABE;
public static long l127 = 0xCAFEBABE;
public static long l128 = 0xCAFEBABE;
public static long l129 = 0xCAFEBABE;
public static long l130 = 0xCAFEBABE;
public static long l131 = 0xCAFEBABE;
public static long l132 = 0xCAFEBABE;
public static long l133 = 0xCAFEBABE;
public static long l134 = 0xCAFEBABE;
public static long l135 = 0xCAFEBABE;
public static long l136 = 0xCAFEBABE;
public static long l137 = 0xCAFEBABE;
public static long l138 = 0xCAFEBABE;
public static long l139 = 0xCAFEBABE;
public static long l140 = 0xCAFEBABE;
public static long l141 = 0xCAFEBABE;
public static long l142 = 0xCAFEBABE;
public static long l143 = 0xCAFEBABE;
public static long l144 = 0xCAFEBABE;
public static long l145 = 0xCAFEBABE;
public static long l146 = 0xCAFEBABE;
public static long l147 = 0xCAFEBABE;
public static long l148 = 0xCAFEBABE;
public static long l149 = 0xCAFEBABE;
public static long l150 = 0xCAFEBABE;
public static long l151 = 0xCAFEBABE;
public static long l152 = 0xCAFEBABE;
public static long l153 = 0xCAFEBABE;
public static long l154 = 0xCAFEBABE;
public static long l155 = 0xCAFEBABE;
public static long l156 = 0xCAFEBABE;
public static long l157 = 0xCAFEBABE;
public static long l158 = 0xCAFEBABE;
public static long l159 = 0xCAFEBABE;
public static long l160 = 0xCAFEBABE;
public static long l161 = 0xCAFEBABE;
public static long l162 = 0xCAFEBABE;
public static long l163 = 0xCAFEBABE;
public static long l164 = 0xCAFEBABE;
public static long l165 = 0xCAFEBABE;
public static long l166 = 0xCAFEBABE;
public static long l167 = 0xCAFEBABE;
public static long l168 = 0xCAFEBABE;
public static long l169 = 0xCAFEBABE;
public static long l170 = 0xCAFEBABE;
public static long l171 = 0xCAFEBABE;
public static long l172 = 0xCAFEBABE;
public static long l173 = 0xCAFEBABE;
public static long l174 = 0xCAFEBABE;
public static long l175 = 0xCAFEBABE;
public static long l176 = 0xCAFEBABE;
public static long l177 = 0xCAFEBABE;
public static long l178 = 0xCAFEBABE;
public static long l179 = 0xCAFEBABE;
public static long l180 = 0xCAFEBABE;
public static long l181 = 0xCAFEBABE;
public static long l182 = 0xCAFEBABE;
public static long l183 = 0xCAFEBABE;
public static long l184 = 0xCAFEBABE;
public static long l185 = 0xCAFEBABE;
public static long l186 = 0xCAFEBABE;
public static long l187 = 0xCAFEBABE;
public static long l188 = 0xCAFEBABE;
public static long l189 = 0xCAFEBABE;
public static long l190 = 0xCAFEBABE;
public static long l191 = 0xCAFEBABE;
public static long l192 = 0xCAFEBABE;
public static long l193 = 0xCAFEBABE;
public static long l194 = 0xCAFEBABE;
public static long l195 = 0xCAFEBABE;
public static long l196 = 0xCAFEBABE;
public static long l197 = 0xCAFEBABE;
public static long l198 = 0xCAFEBABE;
public static long l199 = 0xCAFEBABE;
public static long l200 = 0xCAFEBABE;
public static long l201 = 0xCAFEBABE;
public static long l202 = 0xCAFEBABE;
public static long l203 = 0xCAFEBABE;
public static long l204 = 0xCAFEBABE;
public static long l205 = 0xCAFEBABE;
public static long l206 = 0xCAFEBABE;
public static long l207 = 0xCAFEBABE;
public static long l208 = 0xCAFEBABE;
public static long l209 = 0xCAFEBABE;
public static long l210 = 0xCAFEBABE;
public static long l211 = 0xCAFEBABE;
public static long l212 = 0xCAFEBABE;
public static long l213 = 0xCAFEBABE;
public static long l214 = 0xCAFEBABE;
public static long l215 = 0xCAFEBABE;
public static long l216 = 0xCAFEBABE;
public static long l217 = 0xCAFEBABE;
public static long l218 = 0xCAFEBABE;
public static long l219 = 0xCAFEBABE;
public static long l220 = 0xCAFEBABE;
public static long l221 = 0xCAFEBABE;
public static long l222 = 0xCAFEBABE;
public static long l223 = 0xCAFEBABE;
public static long l224 = 0xCAFEBABE;
public static long l225 = 0xCAFEBABE;
public static long l226 = 0xCAFEBABE;
public static long l227 = 0xCAFEBABE;
public static long l228 = 0xCAFEBABE;
public static long l229 = 0xCAFEBABE;
public static long l230 = 0xCAFEBABE;
public static long l231 = 0xCAFEBABE;
public static long l232 = 0xCAFEBABE;
public static long l233 = 0xCAFEBABE;
public static long l234 = 0xCAFEBABE;
public static long l235 = 0xCAFEBABE;
public static long l236 = 0xCAFEBABE;
public static long l237 = 0xCAFEBABE;
public static long l238 = 0xCAFEBABE;
public static long l239 = 0xCAFEBABE;
public static long l240 = 0xCAFEBABE;
public static long l241 = 0xCAFEBABE;
public static long l242 = 0xCAFEBABE;
public static long l243 = 0xCAFEBABE;
public static long l244 = 0xCAFEBABE;
public static long l245 = 0xCAFEBABE;
public static long l246 = 0xCAFEBABE;
public static long l247 = 0xCAFEBABE;
public static long l248 = 0xCAFEBABE;
public static long l249 = 0xCAFEBABE;
public static long l250 = 0xCAFEBABE;
public static long l251 = 0xCAFEBABE;
public static long l252 = 0xCAFEBABE;
public static long l253 = 0xCAFEBABE;
public static long l254 = 0xCAFEBABE;
public static long l255 = 0xCAFEBABE;
public static long l256 = 0xCAFEBABE;
public static long l257 = 0xCAFEBABE;
public static long l258 = 0xCAFEBABE;
public static long l259 = 0xCAFEBABE;
public static long l260 = 0xCAFEBABE;
public static long l261 = 0xCAFEBABE;
public static long l262 = 0xCAFEBABE;
public static long l263 = 0xCAFEBABE;
public static long l264 = 0xCAFEBABE;
public static long l265 = 0xCAFEBABE;
public static long l266 = 0xCAFEBABE;
public static long l267 = 0xCAFEBABE;
public static long l268 = 0xCAFEBABE;
public static long l269 = 0xCAFEBABE;
public static long l270 = 0xCAFEBABE;
public static long l271 = 0xCAFEBABE;
public static long l272 = 0xCAFEBABE;
public static long l273 = 0xCAFEBABE;
public static long l274 = 0xCAFEBABE;
public static long l275 = 0xCAFEBABE;
public static long l276 = 0xCAFEBABE;
public static long l277 = 0xCAFEBABE;
public static long l278 = 0xCAFEBABE;
public static long l279 = 0xCAFEBABE;
public static long l280 = 0xCAFEBABE;
public static long l281 = 0xCAFEBABE;
public static long l282 = 0xCAFEBABE;
public static long l283 = 0xCAFEBABE;
public static long l284 = 0xCAFEBABE;
public static long l285 = 0xCAFEBABE;
public static long l286 = 0xCAFEBABE;
public static long l287 = 0xCAFEBABE;
public static long l288 = 0xCAFEBABE;
public static long l289 = 0xCAFEBABE;
public static long l290 = 0xCAFEBABE;
public static long l291 = 0xCAFEBABE;
public static long l292 = 0xCAFEBABE;
public static long l293 = 0xCAFEBABE;
public static long l294 = 0xCAFEBABE;
public static long l295 = 0xCAFEBABE;
public static long l296 = 0xCAFEBABE;
public static long l297 = 0xCAFEBABE;
public static long l298 = 0xCAFEBABE;
public static long l299 = 0xCAFEBABE;
public static long l300 = 0xCAFEBABE;
public static long l301 = 0xCAFEBABE;
public static long l302 = 0xCAFEBABE;
public static long l303 = 0xCAFEBABE;
public static long l304 = 0xCAFEBABE;
public static long l305 = 0xCAFEBABE;
public static long l306 = 0xCAFEBABE;
public static long l307 = 0xCAFEBABE;
public static long l308 = 0xCAFEBABE;
public static long l309 = 0xCAFEBABE;
public static long l310 = 0xCAFEBABE;
public static long l311 = 0xCAFEBABE;
public static long l312 = 0xCAFEBABE;
public static long l313 = 0xCAFEBABE;
public static long l314 = 0xCAFEBABE;
public static long l315 = 0xCAFEBABE;
public static long l316 = 0xCAFEBABE;
public static long l317 = 0xCAFEBABE;
public static long l318 = 0xCAFEBABE;
public static long l319 = 0xCAFEBABE;
public static long l320 = 0xCAFEBABE;
public static long l321 = 0xCAFEBABE;
public static long l322 = 0xCAFEBABE;
public static long l323 = 0xCAFEBABE;
public static long l324 = 0xCAFEBABE;
public static long l325 = 0xCAFEBABE;
public static long l326 = 0xCAFEBABE;
public static long l327 = 0xCAFEBABE;
public static long l328 = 0xCAFEBABE;
public static long l329 = 0xCAFEBABE;
public static long l330 = 0xCAFEBABE;
public static long l331 = 0xCAFEBABE;
public static long l332 = 0xCAFEBABE;
public static long l333 = 0xCAFEBABE;
public static long l334 = 0xCAFEBABE;
public static long l335 = 0xCAFEBABE;
public static long l336 = 0xCAFEBABE;
public static long l337 = 0xCAFEBABE;
public static long l338 = 0xCAFEBABE;
public static long l339 = 0xCAFEBABE;
public static long l340 = 0xCAFEBABE;
public static long l341 = 0xCAFEBABE;
public static long l342 = 0xCAFEBABE;
public static long l343 = 0xCAFEBABE;
public static long l344 = 0xCAFEBABE;
public static long l345 = 0xCAFEBABE;
public static long l346 = 0xCAFEBABE;
public static long l347 = 0xCAFEBABE;
public static long l348 = 0xCAFEBABE;
public static long l349 = 0xCAFEBABE;
public static long l350 = 0xCAFEBABE;
public static long l351 = 0xCAFEBABE;
public static long l352 = 0xCAFEBABE;
public static long l353 = 0xCAFEBABE;
public static long l354 = 0xCAFEBABE;
public static long l355 = 0xCAFEBABE;
public static long l356 = 0xCAFEBABE;
public static long l357 = 0xCAFEBABE;
public static long l358 = 0xCAFEBABE;
public static long l359 = 0xCAFEBABE;
public static long l360 = 0xCAFEBABE;
public static long l361 = 0xCAFEBABE;
public static long l362 = 0xCAFEBABE;
public static long l363 = 0xCAFEBABE;
public static long l364 = 0xCAFEBABE;
public static long l365 = 0xCAFEBABE;
public static long l366 = 0xCAFEBABE;
public static long l367 = 0xCAFEBABE;
public static long l368 = 0xCAFEBABE;
public static long l369 = 0xCAFEBABE;
public static long l370 = 0xCAFEBABE;
public static long l371 = 0xCAFEBABE;
public static long l372 = 0xCAFEBABE;
public static long l373 = 0xCAFEBABE;
public static long l374 = 0xCAFEBABE;
public static long l375 = 0xCAFEBABE;
public static long l376 = 0xCAFEBABE;
public static long l377 = 0xCAFEBABE;
public static long l378 = 0xCAFEBABE;
public static long l379 = 0xCAFEBABE;
public static long l380 = 0xCAFEBABE;
public static long l381 = 0xCAFEBABE;
public static long l382 = 0xCAFEBABE;
public static long l383 = 0xCAFEBABE;
public static long l384 = 0xCAFEBABE;
public static long l385 = 0xCAFEBABE;
public static long l386 = 0xCAFEBABE;
public static long l387 = 0xCAFEBABE;
public static long l388 = 0xCAFEBABE;
public static long l389 = 0xCAFEBABE;
public static long l390 = 0xCAFEBABE;
public static long l391 = 0xCAFEBABE;
public static long l392 = 0xCAFEBABE;
public static long l393 = 0xCAFEBABE;
public static long l394 = 0xCAFEBABE;
public static long l395 = 0xCAFEBABE;
public static long l396 = 0xCAFEBABE;
public static long l397 = 0xCAFEBABE;
public static long l398 = 0xCAFEBABE;
public static long l399 = 0xCAFEBABE;
public static long l400 = 0xCAFEBABE;
public static long l401 = 0xCAFEBABE;
public static long l402 = 0xCAFEBABE;
public static long l403 = 0xCAFEBABE;
public static long l404 = 0xCAFEBABE;
public static long l405 = 0xCAFEBABE;
public static long l406 = 0xCAFEBABE;
public static long l407 = 0xCAFEBABE;
public static long l408 = 0xCAFEBABE;
public static long l409 = 0xCAFEBABE;
public static long l410 = 0xCAFEBABE;
public static long l411 = 0xCAFEBABE;
public static long l412 = 0xCAFEBABE;
public static long l413 = 0xCAFEBABE;
public static long l414 = 0xCAFEBABE;
public static long l415 = 0xCAFEBABE;
public static long l416 = 0xCAFEBABE;
public static long l417 = 0xCAFEBABE;
public static long l418 = 0xCAFEBABE;
public static long l419 = 0xCAFEBABE;
public static long l420 = 0xCAFEBABE;
public static long l421 = 0xCAFEBABE;
public static long l422 = 0xCAFEBABE;
public static long l423 = 0xCAFEBABE;
public static long l424 = 0xCAFEBABE;
public static long l425 = 0xCAFEBABE;
public static long l426 = 0xCAFEBABE;
public static long l427 = 0xCAFEBABE;
public static long l428 = 0xCAFEBABE;
public static long l429 = 0xCAFEBABE;
public static long l430 = 0xCAFEBABE;
public static long l431 = 0xCAFEBABE;
public static long l432 = 0xCAFEBABE;
public static long l433 = 0xCAFEBABE;
public static long l434 = 0xCAFEBABE;
public static long l435 = 0xCAFEBABE;
public static long l436 = 0xCAFEBABE;
public static long l437 = 0xCAFEBABE;
public static long l438 = 0xCAFEBABE;
public static long l439 = 0xCAFEBABE;
public static long l440 = 0xCAFEBABE;
public static long l441 = 0xCAFEBABE;
public static long l442 = 0xCAFEBABE;
public static long l443 = 0xCAFEBABE;
public static long l444 = 0xCAFEBABE;
public static long l445 = 0xCAFEBABE;
public static long l446 = 0xCAFEBABE;
public static long l447 = 0xCAFEBABE;
public static long l448 = 0xCAFEBABE;
public static long l449 = 0xCAFEBABE;
public static long l450 = 0xCAFEBABE;
public static long l451 = 0xCAFEBABE;
public static long l452 = 0xCAFEBABE;
public static long l453 = 0xCAFEBABE;
public static long l454 = 0xCAFEBABE;
public static long l455 = 0xCAFEBABE;
public static long l456 = 0xCAFEBABE;
public static long l457 = 0xCAFEBABE;
public static long l458 = 0xCAFEBABE;
public static long l459 = 0xCAFEBABE;
public static long l460 = 0xCAFEBABE;
public static long l461 = 0xCAFEBABE;
public static long l462 = 0xCAFEBABE;
public static long l463 = 0xCAFEBABE;
public static long l464 = 0xCAFEBABE;
public static long l465 = 0xCAFEBABE;
public static long l466 = 0xCAFEBABE;
public static long l467 = 0xCAFEBABE;
public static long l468 = 0xCAFEBABE;
public static long l469 = 0xCAFEBABE;
public static long l470 = 0xCAFEBABE;
public static long l471 = 0xCAFEBABE;
public static long l472 = 0xCAFEBABE;
public static long l473 = 0xCAFEBABE;
public static long l474 = 0xCAFEBABE;
public static long l475 = 0xCAFEBABE;
public static long l476 = 0xCAFEBABE;
public static long l477 = 0xCAFEBABE;
public static long l478 = 0xCAFEBABE;
public static long l479 = 0xCAFEBABE;
public static long l480 = 0xCAFEBABE;
public static long l481 = 0xCAFEBABE;
public static long l482 = 0xCAFEBABE;
public static long l483 = 0xCAFEBABE;
public static long l484 = 0xCAFEBABE;
public static long l485 = 0xCAFEBABE;
public static long l486 = 0xCAFEBABE;
public static long l487 = 0xCAFEBABE;
public static long l488 = 0xCAFEBABE;
public static long l489 = 0xCAFEBABE;
public static long l490 = 0xCAFEBABE;
public static long l491 = 0xCAFEBABE;
public static long l492 = 0xCAFEBABE;
public static long l493 = 0xCAFEBABE;
public static long l494 = 0xCAFEBABE;
public static long l495 = 0xCAFEBABE;
public static long l496 = 0xCAFEBABE;
public static long l497 = 0xCAFEBABE;
public static long l498 = 0xCAFEBABE;
public static long l499 = 0xCAFEBABE;
public static long l500 = 0xCAFEBABE;
public static long l501 = 0xCAFEBABE;
public static long l502 = 0xCAFEBABE;
public static long l503 = 0xCAFEBABE;
public static long l504 = 0xCAFEBABE;
public static long l505 = 0xCAFEBABE;
public static long l506 = 0xCAFEBABE;
public static long l507 = 0xCAFEBABE;
public static long l508 = 0xCAFEBABE;
public static long l509 = 0xCAFEBABE;
public static long l510 = 0xCAFEBABE;
public static long l511 = 0xCAFEBABE;
public static long l512 = 0xCAFEBABE;
public static long l513 = 0xCAFEBABE;
public static long l514 = 0xCAFEBABE;
public static long l515 = 0xCAFEBABE;
public static long l516 = 0xCAFEBABE;
public static long l517 = 0xCAFEBABE;
public static long l518 = 0xCAFEBABE;
public static long l519 = 0xCAFEBABE;
public static long l520 = 0xCAFEBABE;
public static long l521 = 0xCAFEBABE;
public static long l522 = 0xCAFEBABE;
public static long l523 = 0xCAFEBABE;
public static long l524 = 0xCAFEBABE;
public static long l525 = 0xCAFEBABE;
public static long l526 = 0xCAFEBABE;
public static long l527 = 0xCAFEBABE;
public static long l528 = 0xCAFEBABE;
public static long l529 = 0xCAFEBABE;
public static long l530 = 0xCAFEBABE;
public static long l531 = 0xCAFEBABE;
public static long l532 = 0xCAFEBABE;
public static long l533 = 0xCAFEBABE;
public static long l534 = 0xCAFEBABE;
public static long l535 = 0xCAFEBABE;
public static long l536 = 0xCAFEBABE;
public static long l537 = 0xCAFEBABE;
public static long l538 = 0xCAFEBABE;
public static long l539 = 0xCAFEBABE;
public static long l540 = 0xCAFEBABE;
public static long l541 = 0xCAFEBABE;
public static long l542 = 0xCAFEBABE;
public static long l543 = 0xCAFEBABE;
public static long l544 = 0xCAFEBABE;
public static long l545 = 0xCAFEBABE;
public static long l546 = 0xCAFEBABE;
public static long l547 = 0xCAFEBABE;
public static long l548 = 0xCAFEBABE;
public static long l549 = 0xCAFEBABE;
public static long l550 = 0xCAFEBABE;
public static long l551 = 0xCAFEBABE;
public static long l552 = 0xCAFEBABE;
public static long l553 = 0xCAFEBABE;
public static long l554 = 0xCAFEBABE;
public static long l555 = 0xCAFEBABE;
public static long l556 = 0xCAFEBABE;
public static long l557 = 0xCAFEBABE;
public static long l558 = 0xCAFEBABE;
public static long l559 = 0xCAFEBABE;
public static long l560 = 0xCAFEBABE;
public static long l561 = 0xCAFEBABE;
public static long l562 = 0xCAFEBABE;
public static long l563 = 0xCAFEBABE;
public static long l564 = 0xCAFEBABE;
public static long l565 = 0xCAFEBABE;
public static long l566 = 0xCAFEBABE;
public static long l567 = 0xCAFEBABE;
public static long l568 = 0xCAFEBABE;
public static long l569 = 0xCAFEBABE;
public static long l570 = 0xCAFEBABE;
public static long l571 = 0xCAFEBABE;
public static long l572 = 0xCAFEBABE;
public static long l573 = 0xCAFEBABE;
public static long l574 = 0xCAFEBABE;
public static long l575 = 0xCAFEBABE;
public static long l576 = 0xCAFEBABE;
public static long l577 = 0xCAFEBABE;
public static long l578 = 0xCAFEBABE;
public static long l579 = 0xCAFEBABE;
public static long l580 = 0xCAFEBABE;
public static long l581 = 0xCAFEBABE;
public static long l582 = 0xCAFEBABE;
public static long l583 = 0xCAFEBABE;
public static long l584 = 0xCAFEBABE;
public static long l585 = 0xCAFEBABE;
public static long l586 = 0xCAFEBABE;
public static long l587 = 0xCAFEBABE;
public static long l588 = 0xCAFEBABE;
public static long l589 = 0xCAFEBABE;
public static long l590 = 0xCAFEBABE;
public static long l591 = 0xCAFEBABE;
public static long l592 = 0xCAFEBABE;
public static long l593 = 0xCAFEBABE;
public static long l594 = 0xCAFEBABE;
public static long l595 = 0xCAFEBABE;
public static long l596 = 0xCAFEBABE;
public static long l597 = 0xCAFEBABE;
public static long l598 = 0xCAFEBABE;
public static long l599 = 0xCAFEBABE;
public static long l600 = 0xCAFEBABE;
public static long l601 = 0xCAFEBABE;
public static long l602 = 0xCAFEBABE;
public static long l603 = 0xCAFEBABE;
public static long l604 = 0xCAFEBABE;
public static long l605 = 0xCAFEBABE;
public static long l606 = 0xCAFEBABE;
public static long l607 = 0xCAFEBABE;
public static long l608 = 0xCAFEBABE;
public static long l609 = 0xCAFEBABE;
public static long l610 = 0xCAFEBABE;
public static long l611 = 0xCAFEBABE;
public static long l612 = 0xCAFEBABE;
public static long l613 = 0xCAFEBABE;
public static long l614 = 0xCAFEBABE;
public static long l615 = 0xCAFEBABE;
public static long l616 = 0xCAFEBABE;
public static long l617 = 0xCAFEBABE;
public static long l618 = 0xCAFEBABE;
public static long l619 = 0xCAFEBABE;
public static long l620 = 0xCAFEBABE;
public static long l621 = 0xCAFEBABE;
public static long l622 = 0xCAFEBABE;
public static long l623 = 0xCAFEBABE;
public static long l624 = 0xCAFEBABE;
public static long l625 = 0xCAFEBABE;
public static long l626 = 0xCAFEBABE;
public static long l627 = 0xCAFEBABE;
public static long l628 = 0xCAFEBABE;
public static long l629 = 0xCAFEBABE;
public static long l630 = 0xCAFEBABE;
public static long l631 = 0xCAFEBABE;
public static long l632 = 0xCAFEBABE;
public static long l633 = 0xCAFEBABE;
public static long l634 = 0xCAFEBABE;
public static long l635 = 0xCAFEBABE;
public static long l636 = 0xCAFEBABE;
public static long l637 = 0xCAFEBABE;
public static long l638 = 0xCAFEBABE;
public static long l639 = 0xCAFEBABE;
public static long l640 = 0xCAFEBABE;
public static long l641 = 0xCAFEBABE;
public static long l642 = 0xCAFEBABE;
public static long l643 = 0xCAFEBABE;
public static long l644 = 0xCAFEBABE;
public static long l645 = 0xCAFEBABE;
public static long l646 = 0xCAFEBABE;
public static long l647 = 0xCAFEBABE;
public static long l648 = 0xCAFEBABE;
public static long l649 = 0xCAFEBABE;
public static long l650 = 0xCAFEBABE;
public static long l651 = 0xCAFEBABE;
public static long l652 = 0xCAFEBABE;
public static long l653 = 0xCAFEBABE;
public static long l654 = 0xCAFEBABE;
public static long l655 = 0xCAFEBABE;
public static long l656 = 0xCAFEBABE;
public static long l657 = 0xCAFEBABE;
public static long l658 = 0xCAFEBABE;
public static long l659 = 0xCAFEBABE;
public static long l660 = 0xCAFEBABE;
public static long l661 = 0xCAFEBABE;
public static long l662 = 0xCAFEBABE;
public static long l663 = 0xCAFEBABE;
public static long l664 = 0xCAFEBABE;
public static long l665 = 0xCAFEBABE;
public static long l666 = 0xCAFEBABE;
public static long l667 = 0xCAFEBABE;
public static long l668 = 0xCAFEBABE;
public static long l669 = 0xCAFEBABE;
public static long l670 = 0xCAFEBABE;
public static long l671 = 0xCAFEBABE;
public static long l672 = 0xCAFEBABE;
public static long l673 = 0xCAFEBABE;
public static long l674 = 0xCAFEBABE;
public static long l675 = 0xCAFEBABE;
public static long l676 = 0xCAFEBABE;
public static long l677 = 0xCAFEBABE;
public static long l678 = 0xCAFEBABE;
public static long l679 = 0xCAFEBABE;
public static long l680 = 0xCAFEBABE;
public static long l681 = 0xCAFEBABE;
public static long l682 = 0xCAFEBABE;
public static long l683 = 0xCAFEBABE;
public static long l684 = 0xCAFEBABE;
public static long l685 = 0xCAFEBABE;
public static long l686 = 0xCAFEBABE;
public static long l687 = 0xCAFEBABE;
public static long l688 = 0xCAFEBABE;
public static long l689 = 0xCAFEBABE;
public static long l690 = 0xCAFEBABE;
public static long l691 = 0xCAFEBABE;
public static long l692 = 0xCAFEBABE;
public static long l693 = 0xCAFEBABE;
public static long l694 = 0xCAFEBABE;
public static long l695 = 0xCAFEBABE;
public static long l696 = 0xCAFEBABE;
public static long l697 = 0xCAFEBABE;
public static long l698 = 0xCAFEBABE;
public static long l699 = 0xCAFEBABE;
public static long l700 = 0xCAFEBABE;
public static long l701 = 0xCAFEBABE;
public static long l702 = 0xCAFEBABE;
public static long l703 = 0xCAFEBABE;
public static long l704 = 0xCAFEBABE;
public static long l705 = 0xCAFEBABE;
public static long l706 = 0xCAFEBABE;
public static long l707 = 0xCAFEBABE;
public static long l708 = 0xCAFEBABE;
public static long l709 = 0xCAFEBABE;
public static long l710 = 0xCAFEBABE;
public static long l711 = 0xCAFEBABE;
public static long l712 = 0xCAFEBABE;
public static long l713 = 0xCAFEBABE;
public static long l714 = 0xCAFEBABE;
public static long l715 = 0xCAFEBABE;
public static long l716 = 0xCAFEBABE;
public static long l717 = 0xCAFEBABE;
public static long l718 = 0xCAFEBABE;
public static long l719 = 0xCAFEBABE;
public static long l720 = 0xCAFEBABE;
public static long l721 = 0xCAFEBABE;
public static long l722 = 0xCAFEBABE;
public static long l723 = 0xCAFEBABE;
public static long l724 = 0xCAFEBABE;
public static long l725 = 0xCAFEBABE;
public static long l726 = 0xCAFEBABE;
public static long l727 = 0xCAFEBABE;
public static long l728 = 0xCAFEBABE;
public static long l729 = 0xCAFEBABE;
public static long l730 = 0xCAFEBABE;
public static long l731 = 0xCAFEBABE;
public static long l732 = 0xCAFEBABE;
public static long l733 = 0xCAFEBABE;
public static long l734 = 0xCAFEBABE;
public static long l735 = 0xCAFEBABE;
public static long l736 = 0xCAFEBABE;
public static long l737 = 0xCAFEBABE;
public static long l738 = 0xCAFEBABE;
public static long l739 = 0xCAFEBABE;
public static long l740 = 0xCAFEBABE;
public static long l741 = 0xCAFEBABE;
public static long l742 = 0xCAFEBABE;
public static long l743 = 0xCAFEBABE;
public static long l744 = 0xCAFEBABE;
public static long l745 = 0xCAFEBABE;
public static long l746 = 0xCAFEBABE;
public static long l747 = 0xCAFEBABE;
public static long l748 = 0xCAFEBABE;
public static long l749 = 0xCAFEBABE;
public static long l750 = 0xCAFEBABE;
public static long l751 = 0xCAFEBABE;
public static long l752 = 0xCAFEBABE;
public static long l753 = 0xCAFEBABE;
public static long l754 = 0xCAFEBABE;
public static long l755 = 0xCAFEBABE;
public static long l756 = 0xCAFEBABE;
public static long l757 = 0xCAFEBABE;
public static long l758 = 0xCAFEBABE;
public static long l759 = 0xCAFEBABE;
public static long l760 = 0xCAFEBABE;
public static long l761 = 0xCAFEBABE;
public static long l762 = 0xCAFEBABE;
public static long l763 = 0xCAFEBABE;
public static long l764 = 0xCAFEBABE;
public static long l765 = 0xCAFEBABE;
public static long l766 = 0xCAFEBABE;
public static long l767 = 0xCAFEBABE;
public static long l768 = 0xCAFEBABE;
public static long l769 = 0xCAFEBABE;
public static long l770 = 0xCAFEBABE;
public static long l771 = 0xCAFEBABE;
public static long l772 = 0xCAFEBABE;
public static long l773 = 0xCAFEBABE;
public static long l774 = 0xCAFEBABE;
public static long l775 = 0xCAFEBABE;
public static long l776 = 0xCAFEBABE;
public static long l777 = 0xCAFEBABE;
public static long l778 = 0xCAFEBABE;
public static long l779 = 0xCAFEBABE;
public static long l780 = 0xCAFEBABE;
public static long l781 = 0xCAFEBABE;
public static long l782 = 0xCAFEBABE;
public static long l783 = 0xCAFEBABE;
public static long l784 = 0xCAFEBABE;
public static long l785 = 0xCAFEBABE;
public static long l786 = 0xCAFEBABE;
public static long l787 = 0xCAFEBABE;
public static long l788 = 0xCAFEBABE;
public static long l789 = 0xCAFEBABE;
public static long l790 = 0xCAFEBABE;
public static long l791 = 0xCAFEBABE;
public static long l792 = 0xCAFEBABE;
public static long l793 = 0xCAFEBABE;
public static long l794 = 0xCAFEBABE;
public static long l795 = 0xCAFEBABE;
public static long l796 = 0xCAFEBABE;
public static long l797 = 0xCAFEBABE;
public static long l798 = 0xCAFEBABE;
public static long l799 = 0xCAFEBABE;
public static long l800 = 0xCAFEBABE;
public static long l801 = 0xCAFEBABE;
public static long l802 = 0xCAFEBABE;
public static long l803 = 0xCAFEBABE;
public static long l804 = 0xCAFEBABE;
public static long l805 = 0xCAFEBABE;
public static long l806 = 0xCAFEBABE;
public static long l807 = 0xCAFEBABE;
public static long l808 = 0xCAFEBABE;
public static long l809 = 0xCAFEBABE;
public static long l810 = 0xCAFEBABE;
public static long l811 = 0xCAFEBABE;
public static long l812 = 0xCAFEBABE;
public static long l813 = 0xCAFEBABE;
public static long l814 = 0xCAFEBABE;
public static long l815 = 0xCAFEBABE;
public static long l816 = 0xCAFEBABE;
public static long l817 = 0xCAFEBABE;
public static long l818 = 0xCAFEBABE;
public static long l819 = 0xCAFEBABE;
public static long l820 = 0xCAFEBABE;
public static long l821 = 0xCAFEBABE;
public static long l822 = 0xCAFEBABE;
public static long l823 = 0xCAFEBABE;
public static long l824 = 0xCAFEBABE;
public static long l825 = 0xCAFEBABE;
public static long l826 = 0xCAFEBABE;
public static long l827 = 0xCAFEBABE;
public static long l828 = 0xCAFEBABE;
public static long l829 = 0xCAFEBABE;
public static long l830 = 0xCAFEBABE;
public static long l831 = 0xCAFEBABE;
public static long l832 = 0xCAFEBABE;
public static long l833 = 0xCAFEBABE;
public static long l834 = 0xCAFEBABE;
public static long l835 = 0xCAFEBABE;
public static long l836 = 0xCAFEBABE;
public static long l837 = 0xCAFEBABE;
public static long l838 = 0xCAFEBABE;
public static long l839 = 0xCAFEBABE;
public static long l840 = 0xCAFEBABE;
public static long l841 = 0xCAFEBABE;
public static long l842 = 0xCAFEBABE;
public static long l843 = 0xCAFEBABE;
public static long l844 = 0xCAFEBABE;
public static long l845 = 0xCAFEBABE;
public static long l846 = 0xCAFEBABE;
public static long l847 = 0xCAFEBABE;
public static long l848 = 0xCAFEBABE;
public static long l849 = 0xCAFEBABE;
public static long l850 = 0xCAFEBABE;
public static long l851 = 0xCAFEBABE;
public static long l852 = 0xCAFEBABE;
public static long l853 = 0xCAFEBABE;
public static long l854 = 0xCAFEBABE;
public static long l855 = 0xCAFEBABE;
public static long l856 = 0xCAFEBABE;
public static long l857 = 0xCAFEBABE;
public static long l858 = 0xCAFEBABE;
public static long l859 = 0xCAFEBABE;
public static long l860 = 0xCAFEBABE;
public static long l861 = 0xCAFEBABE;
public static long l862 = 0xCAFEBABE;
public static long l863 = 0xCAFEBABE;
public static long l864 = 0xCAFEBABE;
public static long l865 = 0xCAFEBABE;
public static long l866 = 0xCAFEBABE;
public static long l867 = 0xCAFEBABE;
public static long l868 = 0xCAFEBABE;
public static long l869 = 0xCAFEBABE;
public static long l870 = 0xCAFEBABE;
public static long l871 = 0xCAFEBABE;
public static long l872 = 0xCAFEBABE;
public static long l873 = 0xCAFEBABE;
public static long l874 = 0xCAFEBABE;
public static long l875 = 0xCAFEBABE;
public static long l876 = 0xCAFEBABE;
public static long l877 = 0xCAFEBABE;
public static long l878 = 0xCAFEBABE;
public static long l879 = 0xCAFEBABE;
public static long l880 = 0xCAFEBABE;
public static long l881 = 0xCAFEBABE;
public static long l882 = 0xCAFEBABE;
public static long l883 = 0xCAFEBABE;
public static long l884 = 0xCAFEBABE;
public static long l885 = 0xCAFEBABE;
public static long l886 = 0xCAFEBABE;
public static long l887 = 0xCAFEBABE;
public static long l888 = 0xCAFEBABE;
public static long l889 = 0xCAFEBABE;
public static long l890 = 0xCAFEBABE;
public static long l891 = 0xCAFEBABE;
public static long l892 = 0xCAFEBABE;
public static long l893 = 0xCAFEBABE;
public static long l894 = 0xCAFEBABE;
public static long l895 = 0xCAFEBABE;
public static long l896 = 0xCAFEBABE;
public static long l897 = 0xCAFEBABE;
public static long l898 = 0xCAFEBABE;
public static long l899 = 0xCAFEBABE;
public static long l900 = 0xCAFEBABE;
public static long l901 = 0xCAFEBABE;
public static long l902 = 0xCAFEBABE;
public static long l903 = 0xCAFEBABE;
public static long l904 = 0xCAFEBABE;
public static long l905 = 0xCAFEBABE;
public static long l906 = 0xCAFEBABE;
public static long l907 = 0xCAFEBABE;
public static long l908 = 0xCAFEBABE;
public static long l909 = 0xCAFEBABE;
public static long l910 = 0xCAFEBABE;
public static long l911 = 0xCAFEBABE;
public static long l912 = 0xCAFEBABE;
public static long l913 = 0xCAFEBABE;
public static long l914 = 0xCAFEBABE;
public static long l915 = 0xCAFEBABE;
public static long l916 = 0xCAFEBABE;
public static long l917 = 0xCAFEBABE;
public static long l918 = 0xCAFEBABE;
public static long l919 = 0xCAFEBABE;
public static long l920 = 0xCAFEBABE;
public static long l921 = 0xCAFEBABE;
public static long l922 = 0xCAFEBABE;
public static long l923 = 0xCAFEBABE;
public static long l924 = 0xCAFEBABE;
public static long l925 = 0xCAFEBABE;
public static long l926 = 0xCAFEBABE;
public static long l927 = 0xCAFEBABE;
public static long l928 = 0xCAFEBABE;
public static long l929 = 0xCAFEBABE;
public static long l930 = 0xCAFEBABE;
public static long l931 = 0xCAFEBABE;
public static long l932 = 0xCAFEBABE;
public static long l933 = 0xCAFEBABE;
public static long l934 = 0xCAFEBABE;
public static long l935 = 0xCAFEBABE;
public static long l936 = 0xCAFEBABE;
public static long l937 = 0xCAFEBABE;
public static long l938 = 0xCAFEBABE;
public static long l939 = 0xCAFEBABE;
public static long l940 = 0xCAFEBABE;
public static long l941 = 0xCAFEBABE;
public static long l942 = 0xCAFEBABE;
public static long l943 = 0xCAFEBABE;
public static long l944 = 0xCAFEBABE;
public static long l945 = 0xCAFEBABE;
public static long l946 = 0xCAFEBABE;
public static long l947 = 0xCAFEBABE;
public static long l948 = 0xCAFEBABE;
public static long l949 = 0xCAFEBABE;
public static long l950 = 0xCAFEBABE;
public static long l951 = 0xCAFEBABE;
public static long l952 = 0xCAFEBABE;
public static long l953 = 0xCAFEBABE;
public static long l954 = 0xCAFEBABE;
public static long l955 = 0xCAFEBABE;
public static long l956 = 0xCAFEBABE;
public static long l957 = 0xCAFEBABE;
public static long l958 = 0xCAFEBABE;
public static long l959 = 0xCAFEBABE;
public static long l960 = 0xCAFEBABE;
public static long l961 = 0xCAFEBABE;
public static long l962 = 0xCAFEBABE;
public static long l963 = 0xCAFEBABE;
public static long l964 = 0xCAFEBABE;
public static long l965 = 0xCAFEBABE;
public static long l966 = 0xCAFEBABE;
public static long l967 = 0xCAFEBABE;
public static long l968 = 0xCAFEBABE;
public static long l969 = 0xCAFEBABE;
public static long l970 = 0xCAFEBABE;
public static long l971 = 0xCAFEBABE;
public static long l972 = 0xCAFEBABE;
public static long l973 = 0xCAFEBABE;
public static long l974 = 0xCAFEBABE;
public static long l975 = 0xCAFEBABE;
public static long l976 = 0xCAFEBABE;
public static long l977 = 0xCAFEBABE;
public static long l978 = 0xCAFEBABE;
public static long l979 = 0xCAFEBABE;
public static long l980 = 0xCAFEBABE;
public static long l981 = 0xCAFEBABE;
public static long l982 = 0xCAFEBABE;
public static long l983 = 0xCAFEBABE;
public static long l984 = 0xCAFEBABE;
public static long l985 = 0xCAFEBABE;
public static long l986 = 0xCAFEBABE;
public static long l987 = 0xCAFEBABE;
public static long l988 = 0xCAFEBABE;
public static long l989 = 0xCAFEBABE;
public static long l990 = 0xCAFEBABE;
public static long l991 = 0xCAFEBABE;
public static long l992 = 0xCAFEBABE;
public static long l993 = 0xCAFEBABE;
public static long l994 = 0xCAFEBABE;
public static long l995 = 0xCAFEBABE;
public static long l996 = 0xCAFEBABE;
public static long l997 = 0xCAFEBABE;
public static long l998 = 0xCAFEBABE;
public static long l999 = 0xCAFEBABE;
} | 6,370 |
0 | Create_ds/heap-dump-tool/src/test/java/com/paypal/heapdumptool/sanitizer | Create_ds/heap-dump-tool/src/test/java/com/paypal/heapdumptool/sanitizer/example/ClassWithManyInstanceFields.java | package com.paypal.heapdumptool.sanitizer.example;
public class ClassWithManyInstanceFields {
public long l0 = 0xDEADBEEF;
public long l1 = 0xDEADBEEF;
public long l2 = 0xDEADBEEF;
public long l3 = 0xDEADBEEF;
public long l4 = 0xDEADBEEF;
public long l5 = 0xDEADBEEF;
public long l6 = 0xDEADBEEF;
public long l7 = 0xDEADBEEF;
public long l8 = 0xDEADBEEF;
public long l9 = 0xDEADBEEF;
public long l10 = 0xDEADBEEF;
public long l11 = 0xDEADBEEF;
public long l12 = 0xDEADBEEF;
public long l13 = 0xDEADBEEF;
public long l14 = 0xDEADBEEF;
public long l15 = 0xDEADBEEF;
public long l16 = 0xDEADBEEF;
public long l17 = 0xDEADBEEF;
public long l18 = 0xDEADBEEF;
public long l19 = 0xDEADBEEF;
public long l20 = 0xDEADBEEF;
public long l21 = 0xDEADBEEF;
public long l22 = 0xDEADBEEF;
public long l23 = 0xDEADBEEF;
public long l24 = 0xDEADBEEF;
public long l25 = 0xDEADBEEF;
public long l26 = 0xDEADBEEF;
public long l27 = 0xDEADBEEF;
public long l28 = 0xDEADBEEF;
public long l29 = 0xDEADBEEF;
public long l30 = 0xDEADBEEF;
public long l31 = 0xDEADBEEF;
public long l32 = 0xDEADBEEF;
public long l33 = 0xDEADBEEF;
public long l34 = 0xDEADBEEF;
public long l35 = 0xDEADBEEF;
public long l36 = 0xDEADBEEF;
public long l37 = 0xDEADBEEF;
public long l38 = 0xDEADBEEF;
public long l39 = 0xDEADBEEF;
public long l40 = 0xDEADBEEF;
public long l41 = 0xDEADBEEF;
public long l42 = 0xDEADBEEF;
public long l43 = 0xDEADBEEF;
public long l44 = 0xDEADBEEF;
public long l45 = 0xDEADBEEF;
public long l46 = 0xDEADBEEF;
public long l47 = 0xDEADBEEF;
public long l48 = 0xDEADBEEF;
public long l49 = 0xDEADBEEF;
public long l50 = 0xDEADBEEF;
public long l51 = 0xDEADBEEF;
public long l52 = 0xDEADBEEF;
public long l53 = 0xDEADBEEF;
public long l54 = 0xDEADBEEF;
public long l55 = 0xDEADBEEF;
public long l56 = 0xDEADBEEF;
public long l57 = 0xDEADBEEF;
public long l58 = 0xDEADBEEF;
public long l59 = 0xDEADBEEF;
public long l60 = 0xDEADBEEF;
public long l61 = 0xDEADBEEF;
public long l62 = 0xDEADBEEF;
public long l63 = 0xDEADBEEF;
public long l64 = 0xDEADBEEF;
public long l65 = 0xDEADBEEF;
public long l66 = 0xDEADBEEF;
public long l67 = 0xDEADBEEF;
public long l68 = 0xDEADBEEF;
public long l69 = 0xDEADBEEF;
public long l70 = 0xDEADBEEF;
public long l71 = 0xDEADBEEF;
public long l72 = 0xDEADBEEF;
public long l73 = 0xDEADBEEF;
public long l74 = 0xDEADBEEF;
public long l75 = 0xDEADBEEF;
public long l76 = 0xDEADBEEF;
public long l77 = 0xDEADBEEF;
public long l78 = 0xDEADBEEF;
public long l79 = 0xDEADBEEF;
public long l80 = 0xDEADBEEF;
public long l81 = 0xDEADBEEF;
public long l82 = 0xDEADBEEF;
public long l83 = 0xDEADBEEF;
public long l84 = 0xDEADBEEF;
public long l85 = 0xDEADBEEF;
public long l86 = 0xDEADBEEF;
public long l87 = 0xDEADBEEF;
public long l88 = 0xDEADBEEF;
public long l89 = 0xDEADBEEF;
public long l90 = 0xDEADBEEF;
public long l91 = 0xDEADBEEF;
public long l92 = 0xDEADBEEF;
public long l93 = 0xDEADBEEF;
public long l94 = 0xDEADBEEF;
public long l95 = 0xDEADBEEF;
public long l96 = 0xDEADBEEF;
public long l97 = 0xDEADBEEF;
public long l98 = 0xDEADBEEF;
public long l99 = 0xDEADBEEF;
public long l100 = 0xDEADBEEF;
public long l101 = 0xDEADBEEF;
public long l102 = 0xDEADBEEF;
public long l103 = 0xDEADBEEF;
public long l104 = 0xDEADBEEF;
public long l105 = 0xDEADBEEF;
public long l106 = 0xDEADBEEF;
public long l107 = 0xDEADBEEF;
public long l108 = 0xDEADBEEF;
public long l109 = 0xDEADBEEF;
public long l110 = 0xDEADBEEF;
public long l111 = 0xDEADBEEF;
public long l112 = 0xDEADBEEF;
public long l113 = 0xDEADBEEF;
public long l114 = 0xDEADBEEF;
public long l115 = 0xDEADBEEF;
public long l116 = 0xDEADBEEF;
public long l117 = 0xDEADBEEF;
public long l118 = 0xDEADBEEF;
public long l119 = 0xDEADBEEF;
public long l120 = 0xDEADBEEF;
public long l121 = 0xDEADBEEF;
public long l122 = 0xDEADBEEF;
public long l123 = 0xDEADBEEF;
public long l124 = 0xDEADBEEF;
public long l125 = 0xDEADBEEF;
public long l126 = 0xDEADBEEF;
public long l127 = 0xDEADBEEF;
public long l128 = 0xDEADBEEF;
public long l129 = 0xDEADBEEF;
public long l130 = 0xDEADBEEF;
public long l131 = 0xDEADBEEF;
public long l132 = 0xDEADBEEF;
public long l133 = 0xDEADBEEF;
public long l134 = 0xDEADBEEF;
public long l135 = 0xDEADBEEF;
public long l136 = 0xDEADBEEF;
public long l137 = 0xDEADBEEF;
public long l138 = 0xDEADBEEF;
public long l139 = 0xDEADBEEF;
public long l140 = 0xDEADBEEF;
public long l141 = 0xDEADBEEF;
public long l142 = 0xDEADBEEF;
public long l143 = 0xDEADBEEF;
public long l144 = 0xDEADBEEF;
public long l145 = 0xDEADBEEF;
public long l146 = 0xDEADBEEF;
public long l147 = 0xDEADBEEF;
public long l148 = 0xDEADBEEF;
public long l149 = 0xDEADBEEF;
public long l150 = 0xDEADBEEF;
public long l151 = 0xDEADBEEF;
public long l152 = 0xDEADBEEF;
public long l153 = 0xDEADBEEF;
public long l154 = 0xDEADBEEF;
public long l155 = 0xDEADBEEF;
public long l156 = 0xDEADBEEF;
public long l157 = 0xDEADBEEF;
public long l158 = 0xDEADBEEF;
public long l159 = 0xDEADBEEF;
public long l160 = 0xDEADBEEF;
public long l161 = 0xDEADBEEF;
public long l162 = 0xDEADBEEF;
public long l163 = 0xDEADBEEF;
public long l164 = 0xDEADBEEF;
public long l165 = 0xDEADBEEF;
public long l166 = 0xDEADBEEF;
public long l167 = 0xDEADBEEF;
public long l168 = 0xDEADBEEF;
public long l169 = 0xDEADBEEF;
public long l170 = 0xDEADBEEF;
public long l171 = 0xDEADBEEF;
public long l172 = 0xDEADBEEF;
public long l173 = 0xDEADBEEF;
public long l174 = 0xDEADBEEF;
public long l175 = 0xDEADBEEF;
public long l176 = 0xDEADBEEF;
public long l177 = 0xDEADBEEF;
public long l178 = 0xDEADBEEF;
public long l179 = 0xDEADBEEF;
public long l180 = 0xDEADBEEF;
public long l181 = 0xDEADBEEF;
public long l182 = 0xDEADBEEF;
public long l183 = 0xDEADBEEF;
public long l184 = 0xDEADBEEF;
public long l185 = 0xDEADBEEF;
public long l186 = 0xDEADBEEF;
public long l187 = 0xDEADBEEF;
public long l188 = 0xDEADBEEF;
public long l189 = 0xDEADBEEF;
public long l190 = 0xDEADBEEF;
public long l191 = 0xDEADBEEF;
public long l192 = 0xDEADBEEF;
public long l193 = 0xDEADBEEF;
public long l194 = 0xDEADBEEF;
public long l195 = 0xDEADBEEF;
public long l196 = 0xDEADBEEF;
public long l197 = 0xDEADBEEF;
public long l198 = 0xDEADBEEF;
public long l199 = 0xDEADBEEF;
public long l200 = 0xDEADBEEF;
public long l201 = 0xDEADBEEF;
public long l202 = 0xDEADBEEF;
public long l203 = 0xDEADBEEF;
public long l204 = 0xDEADBEEF;
public long l205 = 0xDEADBEEF;
public long l206 = 0xDEADBEEF;
public long l207 = 0xDEADBEEF;
public long l208 = 0xDEADBEEF;
public long l209 = 0xDEADBEEF;
public long l210 = 0xDEADBEEF;
public long l211 = 0xDEADBEEF;
public long l212 = 0xDEADBEEF;
public long l213 = 0xDEADBEEF;
public long l214 = 0xDEADBEEF;
public long l215 = 0xDEADBEEF;
public long l216 = 0xDEADBEEF;
public long l217 = 0xDEADBEEF;
public long l218 = 0xDEADBEEF;
public long l219 = 0xDEADBEEF;
public long l220 = 0xDEADBEEF;
public long l221 = 0xDEADBEEF;
public long l222 = 0xDEADBEEF;
public long l223 = 0xDEADBEEF;
public long l224 = 0xDEADBEEF;
public long l225 = 0xDEADBEEF;
public long l226 = 0xDEADBEEF;
public long l227 = 0xDEADBEEF;
public long l228 = 0xDEADBEEF;
public long l229 = 0xDEADBEEF;
public long l230 = 0xDEADBEEF;
public long l231 = 0xDEADBEEF;
public long l232 = 0xDEADBEEF;
public long l233 = 0xDEADBEEF;
public long l234 = 0xDEADBEEF;
public long l235 = 0xDEADBEEF;
public long l236 = 0xDEADBEEF;
public long l237 = 0xDEADBEEF;
public long l238 = 0xDEADBEEF;
public long l239 = 0xDEADBEEF;
public long l240 = 0xDEADBEEF;
public long l241 = 0xDEADBEEF;
public long l242 = 0xDEADBEEF;
public long l243 = 0xDEADBEEF;
public long l244 = 0xDEADBEEF;
public long l245 = 0xDEADBEEF;
public long l246 = 0xDEADBEEF;
public long l247 = 0xDEADBEEF;
public long l248 = 0xDEADBEEF;
public long l249 = 0xDEADBEEF;
public long l250 = 0xDEADBEEF;
public long l251 = 0xDEADBEEF;
public long l252 = 0xDEADBEEF;
public long l253 = 0xDEADBEEF;
public long l254 = 0xDEADBEEF;
public long l255 = 0xDEADBEEF;
public long l256 = 0xDEADBEEF;
public long l257 = 0xDEADBEEF;
public long l258 = 0xDEADBEEF;
public long l259 = 0xDEADBEEF;
public long l260 = 0xDEADBEEF;
public long l261 = 0xDEADBEEF;
public long l262 = 0xDEADBEEF;
public long l263 = 0xDEADBEEF;
public long l264 = 0xDEADBEEF;
public long l265 = 0xDEADBEEF;
public long l266 = 0xDEADBEEF;
public long l267 = 0xDEADBEEF;
public long l268 = 0xDEADBEEF;
public long l269 = 0xDEADBEEF;
public long l270 = 0xDEADBEEF;
public long l271 = 0xDEADBEEF;
public long l272 = 0xDEADBEEF;
public long l273 = 0xDEADBEEF;
public long l274 = 0xDEADBEEF;
public long l275 = 0xDEADBEEF;
public long l276 = 0xDEADBEEF;
public long l277 = 0xDEADBEEF;
public long l278 = 0xDEADBEEF;
public long l279 = 0xDEADBEEF;
public long l280 = 0xDEADBEEF;
public long l281 = 0xDEADBEEF;
public long l282 = 0xDEADBEEF;
public long l283 = 0xDEADBEEF;
public long l284 = 0xDEADBEEF;
public long l285 = 0xDEADBEEF;
public long l286 = 0xDEADBEEF;
public long l287 = 0xDEADBEEF;
public long l288 = 0xDEADBEEF;
public long l289 = 0xDEADBEEF;
public long l290 = 0xDEADBEEF;
public long l291 = 0xDEADBEEF;
public long l292 = 0xDEADBEEF;
public long l293 = 0xDEADBEEF;
public long l294 = 0xDEADBEEF;
public long l295 = 0xDEADBEEF;
public long l296 = 0xDEADBEEF;
public long l297 = 0xDEADBEEF;
public long l298 = 0xDEADBEEF;
public long l299 = 0xDEADBEEF;
public long l300 = 0xDEADBEEF;
public long l301 = 0xDEADBEEF;
public long l302 = 0xDEADBEEF;
public long l303 = 0xDEADBEEF;
public long l304 = 0xDEADBEEF;
public long l305 = 0xDEADBEEF;
public long l306 = 0xDEADBEEF;
public long l307 = 0xDEADBEEF;
public long l308 = 0xDEADBEEF;
public long l309 = 0xDEADBEEF;
public long l310 = 0xDEADBEEF;
public long l311 = 0xDEADBEEF;
public long l312 = 0xDEADBEEF;
public long l313 = 0xDEADBEEF;
public long l314 = 0xDEADBEEF;
public long l315 = 0xDEADBEEF;
public long l316 = 0xDEADBEEF;
public long l317 = 0xDEADBEEF;
public long l318 = 0xDEADBEEF;
public long l319 = 0xDEADBEEF;
public long l320 = 0xDEADBEEF;
public long l321 = 0xDEADBEEF;
public long l322 = 0xDEADBEEF;
public long l323 = 0xDEADBEEF;
public long l324 = 0xDEADBEEF;
public long l325 = 0xDEADBEEF;
public long l326 = 0xDEADBEEF;
public long l327 = 0xDEADBEEF;
public long l328 = 0xDEADBEEF;
public long l329 = 0xDEADBEEF;
public long l330 = 0xDEADBEEF;
public long l331 = 0xDEADBEEF;
public long l332 = 0xDEADBEEF;
public long l333 = 0xDEADBEEF;
public long l334 = 0xDEADBEEF;
public long l335 = 0xDEADBEEF;
public long l336 = 0xDEADBEEF;
public long l337 = 0xDEADBEEF;
public long l338 = 0xDEADBEEF;
public long l339 = 0xDEADBEEF;
public long l340 = 0xDEADBEEF;
public long l341 = 0xDEADBEEF;
public long l342 = 0xDEADBEEF;
public long l343 = 0xDEADBEEF;
public long l344 = 0xDEADBEEF;
public long l345 = 0xDEADBEEF;
public long l346 = 0xDEADBEEF;
public long l347 = 0xDEADBEEF;
public long l348 = 0xDEADBEEF;
public long l349 = 0xDEADBEEF;
public long l350 = 0xDEADBEEF;
public long l351 = 0xDEADBEEF;
public long l352 = 0xDEADBEEF;
public long l353 = 0xDEADBEEF;
public long l354 = 0xDEADBEEF;
public long l355 = 0xDEADBEEF;
public long l356 = 0xDEADBEEF;
public long l357 = 0xDEADBEEF;
public long l358 = 0xDEADBEEF;
public long l359 = 0xDEADBEEF;
public long l360 = 0xDEADBEEF;
public long l361 = 0xDEADBEEF;
public long l362 = 0xDEADBEEF;
public long l363 = 0xDEADBEEF;
public long l364 = 0xDEADBEEF;
public long l365 = 0xDEADBEEF;
public long l366 = 0xDEADBEEF;
public long l367 = 0xDEADBEEF;
public long l368 = 0xDEADBEEF;
public long l369 = 0xDEADBEEF;
public long l370 = 0xDEADBEEF;
public long l371 = 0xDEADBEEF;
public long l372 = 0xDEADBEEF;
public long l373 = 0xDEADBEEF;
public long l374 = 0xDEADBEEF;
public long l375 = 0xDEADBEEF;
public long l376 = 0xDEADBEEF;
public long l377 = 0xDEADBEEF;
public long l378 = 0xDEADBEEF;
public long l379 = 0xDEADBEEF;
public long l380 = 0xDEADBEEF;
public long l381 = 0xDEADBEEF;
public long l382 = 0xDEADBEEF;
public long l383 = 0xDEADBEEF;
public long l384 = 0xDEADBEEF;
public long l385 = 0xDEADBEEF;
public long l386 = 0xDEADBEEF;
public long l387 = 0xDEADBEEF;
public long l388 = 0xDEADBEEF;
public long l389 = 0xDEADBEEF;
public long l390 = 0xDEADBEEF;
public long l391 = 0xDEADBEEF;
public long l392 = 0xDEADBEEF;
public long l393 = 0xDEADBEEF;
public long l394 = 0xDEADBEEF;
public long l395 = 0xDEADBEEF;
public long l396 = 0xDEADBEEF;
public long l397 = 0xDEADBEEF;
public long l398 = 0xDEADBEEF;
public long l399 = 0xDEADBEEF;
public long l400 = 0xDEADBEEF;
public long l401 = 0xDEADBEEF;
public long l402 = 0xDEADBEEF;
public long l403 = 0xDEADBEEF;
public long l404 = 0xDEADBEEF;
public long l405 = 0xDEADBEEF;
public long l406 = 0xDEADBEEF;
public long l407 = 0xDEADBEEF;
public long l408 = 0xDEADBEEF;
public long l409 = 0xDEADBEEF;
public long l410 = 0xDEADBEEF;
public long l411 = 0xDEADBEEF;
public long l412 = 0xDEADBEEF;
public long l413 = 0xDEADBEEF;
public long l414 = 0xDEADBEEF;
public long l415 = 0xDEADBEEF;
public long l416 = 0xDEADBEEF;
public long l417 = 0xDEADBEEF;
public long l418 = 0xDEADBEEF;
public long l419 = 0xDEADBEEF;
public long l420 = 0xDEADBEEF;
public long l421 = 0xDEADBEEF;
public long l422 = 0xDEADBEEF;
public long l423 = 0xDEADBEEF;
public long l424 = 0xDEADBEEF;
public long l425 = 0xDEADBEEF;
public long l426 = 0xDEADBEEF;
public long l427 = 0xDEADBEEF;
public long l428 = 0xDEADBEEF;
public long l429 = 0xDEADBEEF;
public long l430 = 0xDEADBEEF;
public long l431 = 0xDEADBEEF;
public long l432 = 0xDEADBEEF;
public long l433 = 0xDEADBEEF;
public long l434 = 0xDEADBEEF;
public long l435 = 0xDEADBEEF;
public long l436 = 0xDEADBEEF;
public long l437 = 0xDEADBEEF;
public long l438 = 0xDEADBEEF;
public long l439 = 0xDEADBEEF;
public long l440 = 0xDEADBEEF;
public long l441 = 0xDEADBEEF;
public long l442 = 0xDEADBEEF;
public long l443 = 0xDEADBEEF;
public long l444 = 0xDEADBEEF;
public long l445 = 0xDEADBEEF;
public long l446 = 0xDEADBEEF;
public long l447 = 0xDEADBEEF;
public long l448 = 0xDEADBEEF;
public long l449 = 0xDEADBEEF;
public long l450 = 0xDEADBEEF;
public long l451 = 0xDEADBEEF;
public long l452 = 0xDEADBEEF;
public long l453 = 0xDEADBEEF;
public long l454 = 0xDEADBEEF;
public long l455 = 0xDEADBEEF;
public long l456 = 0xDEADBEEF;
public long l457 = 0xDEADBEEF;
public long l458 = 0xDEADBEEF;
public long l459 = 0xDEADBEEF;
public long l460 = 0xDEADBEEF;
public long l461 = 0xDEADBEEF;
public long l462 = 0xDEADBEEF;
public long l463 = 0xDEADBEEF;
public long l464 = 0xDEADBEEF;
public long l465 = 0xDEADBEEF;
public long l466 = 0xDEADBEEF;
public long l467 = 0xDEADBEEF;
public long l468 = 0xDEADBEEF;
public long l469 = 0xDEADBEEF;
public long l470 = 0xDEADBEEF;
public long l471 = 0xDEADBEEF;
public long l472 = 0xDEADBEEF;
public long l473 = 0xDEADBEEF;
public long l474 = 0xDEADBEEF;
public long l475 = 0xDEADBEEF;
public long l476 = 0xDEADBEEF;
public long l477 = 0xDEADBEEF;
public long l478 = 0xDEADBEEF;
public long l479 = 0xDEADBEEF;
public long l480 = 0xDEADBEEF;
public long l481 = 0xDEADBEEF;
public long l482 = 0xDEADBEEF;
public long l483 = 0xDEADBEEF;
public long l484 = 0xDEADBEEF;
public long l485 = 0xDEADBEEF;
public long l486 = 0xDEADBEEF;
public long l487 = 0xDEADBEEF;
public long l488 = 0xDEADBEEF;
public long l489 = 0xDEADBEEF;
public long l490 = 0xDEADBEEF;
public long l491 = 0xDEADBEEF;
public long l492 = 0xDEADBEEF;
public long l493 = 0xDEADBEEF;
public long l494 = 0xDEADBEEF;
public long l495 = 0xDEADBEEF;
public long l496 = 0xDEADBEEF;
public long l497 = 0xDEADBEEF;
public long l498 = 0xDEADBEEF;
public long l499 = 0xDEADBEEF;
public long l500 = 0xDEADBEEF;
public long l501 = 0xDEADBEEF;
public long l502 = 0xDEADBEEF;
public long l503 = 0xDEADBEEF;
public long l504 = 0xDEADBEEF;
public long l505 = 0xDEADBEEF;
public long l506 = 0xDEADBEEF;
public long l507 = 0xDEADBEEF;
public long l508 = 0xDEADBEEF;
public long l509 = 0xDEADBEEF;
public long l510 = 0xDEADBEEF;
public long l511 = 0xDEADBEEF;
public long l512 = 0xDEADBEEF;
public long l513 = 0xDEADBEEF;
public long l514 = 0xDEADBEEF;
public long l515 = 0xDEADBEEF;
public long l516 = 0xDEADBEEF;
public long l517 = 0xDEADBEEF;
public long l518 = 0xDEADBEEF;
public long l519 = 0xDEADBEEF;
public long l520 = 0xDEADBEEF;
public long l521 = 0xDEADBEEF;
public long l522 = 0xDEADBEEF;
public long l523 = 0xDEADBEEF;
public long l524 = 0xDEADBEEF;
public long l525 = 0xDEADBEEF;
public long l526 = 0xDEADBEEF;
public long l527 = 0xDEADBEEF;
public long l528 = 0xDEADBEEF;
public long l529 = 0xDEADBEEF;
public long l530 = 0xDEADBEEF;
public long l531 = 0xDEADBEEF;
public long l532 = 0xDEADBEEF;
public long l533 = 0xDEADBEEF;
public long l534 = 0xDEADBEEF;
public long l535 = 0xDEADBEEF;
public long l536 = 0xDEADBEEF;
public long l537 = 0xDEADBEEF;
public long l538 = 0xDEADBEEF;
public long l539 = 0xDEADBEEF;
public long l540 = 0xDEADBEEF;
public long l541 = 0xDEADBEEF;
public long l542 = 0xDEADBEEF;
public long l543 = 0xDEADBEEF;
public long l544 = 0xDEADBEEF;
public long l545 = 0xDEADBEEF;
public long l546 = 0xDEADBEEF;
public long l547 = 0xDEADBEEF;
public long l548 = 0xDEADBEEF;
public long l549 = 0xDEADBEEF;
public long l550 = 0xDEADBEEF;
public long l551 = 0xDEADBEEF;
public long l552 = 0xDEADBEEF;
public long l553 = 0xDEADBEEF;
public long l554 = 0xDEADBEEF;
public long l555 = 0xDEADBEEF;
public long l556 = 0xDEADBEEF;
public long l557 = 0xDEADBEEF;
public long l558 = 0xDEADBEEF;
public long l559 = 0xDEADBEEF;
public long l560 = 0xDEADBEEF;
public long l561 = 0xDEADBEEF;
public long l562 = 0xDEADBEEF;
public long l563 = 0xDEADBEEF;
public long l564 = 0xDEADBEEF;
public long l565 = 0xDEADBEEF;
public long l566 = 0xDEADBEEF;
public long l567 = 0xDEADBEEF;
public long l568 = 0xDEADBEEF;
public long l569 = 0xDEADBEEF;
public long l570 = 0xDEADBEEF;
public long l571 = 0xDEADBEEF;
public long l572 = 0xDEADBEEF;
public long l573 = 0xDEADBEEF;
public long l574 = 0xDEADBEEF;
public long l575 = 0xDEADBEEF;
public long l576 = 0xDEADBEEF;
public long l577 = 0xDEADBEEF;
public long l578 = 0xDEADBEEF;
public long l579 = 0xDEADBEEF;
public long l580 = 0xDEADBEEF;
public long l581 = 0xDEADBEEF;
public long l582 = 0xDEADBEEF;
public long l583 = 0xDEADBEEF;
public long l584 = 0xDEADBEEF;
public long l585 = 0xDEADBEEF;
public long l586 = 0xDEADBEEF;
public long l587 = 0xDEADBEEF;
public long l588 = 0xDEADBEEF;
public long l589 = 0xDEADBEEF;
public long l590 = 0xDEADBEEF;
public long l591 = 0xDEADBEEF;
public long l592 = 0xDEADBEEF;
public long l593 = 0xDEADBEEF;
public long l594 = 0xDEADBEEF;
public long l595 = 0xDEADBEEF;
public long l596 = 0xDEADBEEF;
public long l597 = 0xDEADBEEF;
public long l598 = 0xDEADBEEF;
public long l599 = 0xDEADBEEF;
public long l600 = 0xDEADBEEF;
public long l601 = 0xDEADBEEF;
public long l602 = 0xDEADBEEF;
public long l603 = 0xDEADBEEF;
public long l604 = 0xDEADBEEF;
public long l605 = 0xDEADBEEF;
public long l606 = 0xDEADBEEF;
public long l607 = 0xDEADBEEF;
public long l608 = 0xDEADBEEF;
public long l609 = 0xDEADBEEF;
public long l610 = 0xDEADBEEF;
public long l611 = 0xDEADBEEF;
public long l612 = 0xDEADBEEF;
public long l613 = 0xDEADBEEF;
public long l614 = 0xDEADBEEF;
public long l615 = 0xDEADBEEF;
public long l616 = 0xDEADBEEF;
public long l617 = 0xDEADBEEF;
public long l618 = 0xDEADBEEF;
public long l619 = 0xDEADBEEF;
public long l620 = 0xDEADBEEF;
public long l621 = 0xDEADBEEF;
public long l622 = 0xDEADBEEF;
public long l623 = 0xDEADBEEF;
public long l624 = 0xDEADBEEF;
public long l625 = 0xDEADBEEF;
public long l626 = 0xDEADBEEF;
public long l627 = 0xDEADBEEF;
public long l628 = 0xDEADBEEF;
public long l629 = 0xDEADBEEF;
public long l630 = 0xDEADBEEF;
public long l631 = 0xDEADBEEF;
public long l632 = 0xDEADBEEF;
public long l633 = 0xDEADBEEF;
public long l634 = 0xDEADBEEF;
public long l635 = 0xDEADBEEF;
public long l636 = 0xDEADBEEF;
public long l637 = 0xDEADBEEF;
public long l638 = 0xDEADBEEF;
public long l639 = 0xDEADBEEF;
public long l640 = 0xDEADBEEF;
public long l641 = 0xDEADBEEF;
public long l642 = 0xDEADBEEF;
public long l643 = 0xDEADBEEF;
public long l644 = 0xDEADBEEF;
public long l645 = 0xDEADBEEF;
public long l646 = 0xDEADBEEF;
public long l647 = 0xDEADBEEF;
public long l648 = 0xDEADBEEF;
public long l649 = 0xDEADBEEF;
public long l650 = 0xDEADBEEF;
public long l651 = 0xDEADBEEF;
public long l652 = 0xDEADBEEF;
public long l653 = 0xDEADBEEF;
public long l654 = 0xDEADBEEF;
public long l655 = 0xDEADBEEF;
public long l656 = 0xDEADBEEF;
public long l657 = 0xDEADBEEF;
public long l658 = 0xDEADBEEF;
public long l659 = 0xDEADBEEF;
public long l660 = 0xDEADBEEF;
public long l661 = 0xDEADBEEF;
public long l662 = 0xDEADBEEF;
public long l663 = 0xDEADBEEF;
public long l664 = 0xDEADBEEF;
public long l665 = 0xDEADBEEF;
public long l666 = 0xDEADBEEF;
public long l667 = 0xDEADBEEF;
public long l668 = 0xDEADBEEF;
public long l669 = 0xDEADBEEF;
public long l670 = 0xDEADBEEF;
public long l671 = 0xDEADBEEF;
public long l672 = 0xDEADBEEF;
public long l673 = 0xDEADBEEF;
public long l674 = 0xDEADBEEF;
public long l675 = 0xDEADBEEF;
public long l676 = 0xDEADBEEF;
public long l677 = 0xDEADBEEF;
public long l678 = 0xDEADBEEF;
public long l679 = 0xDEADBEEF;
public long l680 = 0xDEADBEEF;
public long l681 = 0xDEADBEEF;
public long l682 = 0xDEADBEEF;
public long l683 = 0xDEADBEEF;
public long l684 = 0xDEADBEEF;
public long l685 = 0xDEADBEEF;
public long l686 = 0xDEADBEEF;
public long l687 = 0xDEADBEEF;
public long l688 = 0xDEADBEEF;
public long l689 = 0xDEADBEEF;
public long l690 = 0xDEADBEEF;
public long l691 = 0xDEADBEEF;
public long l692 = 0xDEADBEEF;
public long l693 = 0xDEADBEEF;
public long l694 = 0xDEADBEEF;
public long l695 = 0xDEADBEEF;
public long l696 = 0xDEADBEEF;
public long l697 = 0xDEADBEEF;
public long l698 = 0xDEADBEEF;
public long l699 = 0xDEADBEEF;
public long l700 = 0xDEADBEEF;
public long l701 = 0xDEADBEEF;
public long l702 = 0xDEADBEEF;
public long l703 = 0xDEADBEEF;
public long l704 = 0xDEADBEEF;
public long l705 = 0xDEADBEEF;
public long l706 = 0xDEADBEEF;
public long l707 = 0xDEADBEEF;
public long l708 = 0xDEADBEEF;
public long l709 = 0xDEADBEEF;
public long l710 = 0xDEADBEEF;
public long l711 = 0xDEADBEEF;
public long l712 = 0xDEADBEEF;
public long l713 = 0xDEADBEEF;
public long l714 = 0xDEADBEEF;
public long l715 = 0xDEADBEEF;
public long l716 = 0xDEADBEEF;
public long l717 = 0xDEADBEEF;
public long l718 = 0xDEADBEEF;
public long l719 = 0xDEADBEEF;
public long l720 = 0xDEADBEEF;
public long l721 = 0xDEADBEEF;
public long l722 = 0xDEADBEEF;
public long l723 = 0xDEADBEEF;
public long l724 = 0xDEADBEEF;
public long l725 = 0xDEADBEEF;
public long l726 = 0xDEADBEEF;
public long l727 = 0xDEADBEEF;
public long l728 = 0xDEADBEEF;
public long l729 = 0xDEADBEEF;
public long l730 = 0xDEADBEEF;
public long l731 = 0xDEADBEEF;
public long l732 = 0xDEADBEEF;
public long l733 = 0xDEADBEEF;
public long l734 = 0xDEADBEEF;
public long l735 = 0xDEADBEEF;
public long l736 = 0xDEADBEEF;
public long l737 = 0xDEADBEEF;
public long l738 = 0xDEADBEEF;
public long l739 = 0xDEADBEEF;
public long l740 = 0xDEADBEEF;
public long l741 = 0xDEADBEEF;
public long l742 = 0xDEADBEEF;
public long l743 = 0xDEADBEEF;
public long l744 = 0xDEADBEEF;
public long l745 = 0xDEADBEEF;
public long l746 = 0xDEADBEEF;
public long l747 = 0xDEADBEEF;
public long l748 = 0xDEADBEEF;
public long l749 = 0xDEADBEEF;
public long l750 = 0xDEADBEEF;
public long l751 = 0xDEADBEEF;
public long l752 = 0xDEADBEEF;
public long l753 = 0xDEADBEEF;
public long l754 = 0xDEADBEEF;
public long l755 = 0xDEADBEEF;
public long l756 = 0xDEADBEEF;
public long l757 = 0xDEADBEEF;
public long l758 = 0xDEADBEEF;
public long l759 = 0xDEADBEEF;
public long l760 = 0xDEADBEEF;
public long l761 = 0xDEADBEEF;
public long l762 = 0xDEADBEEF;
public long l763 = 0xDEADBEEF;
public long l764 = 0xDEADBEEF;
public long l765 = 0xDEADBEEF;
public long l766 = 0xDEADBEEF;
public long l767 = 0xDEADBEEF;
public long l768 = 0xDEADBEEF;
public long l769 = 0xDEADBEEF;
public long l770 = 0xDEADBEEF;
public long l771 = 0xDEADBEEF;
public long l772 = 0xDEADBEEF;
public long l773 = 0xDEADBEEF;
public long l774 = 0xDEADBEEF;
public long l775 = 0xDEADBEEF;
public long l776 = 0xDEADBEEF;
public long l777 = 0xDEADBEEF;
public long l778 = 0xDEADBEEF;
public long l779 = 0xDEADBEEF;
public long l780 = 0xDEADBEEF;
public long l781 = 0xDEADBEEF;
public long l782 = 0xDEADBEEF;
public long l783 = 0xDEADBEEF;
public long l784 = 0xDEADBEEF;
public long l785 = 0xDEADBEEF;
public long l786 = 0xDEADBEEF;
public long l787 = 0xDEADBEEF;
public long l788 = 0xDEADBEEF;
public long l789 = 0xDEADBEEF;
public long l790 = 0xDEADBEEF;
public long l791 = 0xDEADBEEF;
public long l792 = 0xDEADBEEF;
public long l793 = 0xDEADBEEF;
public long l794 = 0xDEADBEEF;
public long l795 = 0xDEADBEEF;
public long l796 = 0xDEADBEEF;
public long l797 = 0xDEADBEEF;
public long l798 = 0xDEADBEEF;
public long l799 = 0xDEADBEEF;
public long l800 = 0xDEADBEEF;
public long l801 = 0xDEADBEEF;
public long l802 = 0xDEADBEEF;
public long l803 = 0xDEADBEEF;
public long l804 = 0xDEADBEEF;
public long l805 = 0xDEADBEEF;
public long l806 = 0xDEADBEEF;
public long l807 = 0xDEADBEEF;
public long l808 = 0xDEADBEEF;
public long l809 = 0xDEADBEEF;
public long l810 = 0xDEADBEEF;
public long l811 = 0xDEADBEEF;
public long l812 = 0xDEADBEEF;
public long l813 = 0xDEADBEEF;
public long l814 = 0xDEADBEEF;
public long l815 = 0xDEADBEEF;
public long l816 = 0xDEADBEEF;
public long l817 = 0xDEADBEEF;
public long l818 = 0xDEADBEEF;
public long l819 = 0xDEADBEEF;
public long l820 = 0xDEADBEEF;
public long l821 = 0xDEADBEEF;
public long l822 = 0xDEADBEEF;
public long l823 = 0xDEADBEEF;
public long l824 = 0xDEADBEEF;
public long l825 = 0xDEADBEEF;
public long l826 = 0xDEADBEEF;
public long l827 = 0xDEADBEEF;
public long l828 = 0xDEADBEEF;
public long l829 = 0xDEADBEEF;
public long l830 = 0xDEADBEEF;
public long l831 = 0xDEADBEEF;
public long l832 = 0xDEADBEEF;
public long l833 = 0xDEADBEEF;
public long l834 = 0xDEADBEEF;
public long l835 = 0xDEADBEEF;
public long l836 = 0xDEADBEEF;
public long l837 = 0xDEADBEEF;
public long l838 = 0xDEADBEEF;
public long l839 = 0xDEADBEEF;
public long l840 = 0xDEADBEEF;
public long l841 = 0xDEADBEEF;
public long l842 = 0xDEADBEEF;
public long l843 = 0xDEADBEEF;
public long l844 = 0xDEADBEEF;
public long l845 = 0xDEADBEEF;
public long l846 = 0xDEADBEEF;
public long l847 = 0xDEADBEEF;
public long l848 = 0xDEADBEEF;
public long l849 = 0xDEADBEEF;
public long l850 = 0xDEADBEEF;
public long l851 = 0xDEADBEEF;
public long l852 = 0xDEADBEEF;
public long l853 = 0xDEADBEEF;
public long l854 = 0xDEADBEEF;
public long l855 = 0xDEADBEEF;
public long l856 = 0xDEADBEEF;
public long l857 = 0xDEADBEEF;
public long l858 = 0xDEADBEEF;
public long l859 = 0xDEADBEEF;
public long l860 = 0xDEADBEEF;
public long l861 = 0xDEADBEEF;
public long l862 = 0xDEADBEEF;
public long l863 = 0xDEADBEEF;
public long l864 = 0xDEADBEEF;
public long l865 = 0xDEADBEEF;
public long l866 = 0xDEADBEEF;
public long l867 = 0xDEADBEEF;
public long l868 = 0xDEADBEEF;
public long l869 = 0xDEADBEEF;
public long l870 = 0xDEADBEEF;
public long l871 = 0xDEADBEEF;
public long l872 = 0xDEADBEEF;
public long l873 = 0xDEADBEEF;
public long l874 = 0xDEADBEEF;
public long l875 = 0xDEADBEEF;
public long l876 = 0xDEADBEEF;
public long l877 = 0xDEADBEEF;
public long l878 = 0xDEADBEEF;
public long l879 = 0xDEADBEEF;
public long l880 = 0xDEADBEEF;
public long l881 = 0xDEADBEEF;
public long l882 = 0xDEADBEEF;
public long l883 = 0xDEADBEEF;
public long l884 = 0xDEADBEEF;
public long l885 = 0xDEADBEEF;
public long l886 = 0xDEADBEEF;
public long l887 = 0xDEADBEEF;
public long l888 = 0xDEADBEEF;
public long l889 = 0xDEADBEEF;
public long l890 = 0xDEADBEEF;
public long l891 = 0xDEADBEEF;
public long l892 = 0xDEADBEEF;
public long l893 = 0xDEADBEEF;
public long l894 = 0xDEADBEEF;
public long l895 = 0xDEADBEEF;
public long l896 = 0xDEADBEEF;
public long l897 = 0xDEADBEEF;
public long l898 = 0xDEADBEEF;
public long l899 = 0xDEADBEEF;
public long l900 = 0xDEADBEEF;
public long l901 = 0xDEADBEEF;
public long l902 = 0xDEADBEEF;
public long l903 = 0xDEADBEEF;
public long l904 = 0xDEADBEEF;
public long l905 = 0xDEADBEEF;
public long l906 = 0xDEADBEEF;
public long l907 = 0xDEADBEEF;
public long l908 = 0xDEADBEEF;
public long l909 = 0xDEADBEEF;
public long l910 = 0xDEADBEEF;
public long l911 = 0xDEADBEEF;
public long l912 = 0xDEADBEEF;
public long l913 = 0xDEADBEEF;
public long l914 = 0xDEADBEEF;
public long l915 = 0xDEADBEEF;
public long l916 = 0xDEADBEEF;
public long l917 = 0xDEADBEEF;
public long l918 = 0xDEADBEEF;
public long l919 = 0xDEADBEEF;
public long l920 = 0xDEADBEEF;
public long l921 = 0xDEADBEEF;
public long l922 = 0xDEADBEEF;
public long l923 = 0xDEADBEEF;
public long l924 = 0xDEADBEEF;
public long l925 = 0xDEADBEEF;
public long l926 = 0xDEADBEEF;
public long l927 = 0xDEADBEEF;
public long l928 = 0xDEADBEEF;
public long l929 = 0xDEADBEEF;
public long l930 = 0xDEADBEEF;
public long l931 = 0xDEADBEEF;
public long l932 = 0xDEADBEEF;
public long l933 = 0xDEADBEEF;
public long l934 = 0xDEADBEEF;
public long l935 = 0xDEADBEEF;
public long l936 = 0xDEADBEEF;
public long l937 = 0xDEADBEEF;
public long l938 = 0xDEADBEEF;
public long l939 = 0xDEADBEEF;
public long l940 = 0xDEADBEEF;
public long l941 = 0xDEADBEEF;
public long l942 = 0xDEADBEEF;
public long l943 = 0xDEADBEEF;
public long l944 = 0xDEADBEEF;
public long l945 = 0xDEADBEEF;
public long l946 = 0xDEADBEEF;
public long l947 = 0xDEADBEEF;
public long l948 = 0xDEADBEEF;
public long l949 = 0xDEADBEEF;
public long l950 = 0xDEADBEEF;
public long l951 = 0xDEADBEEF;
public long l952 = 0xDEADBEEF;
public long l953 = 0xDEADBEEF;
public long l954 = 0xDEADBEEF;
public long l955 = 0xDEADBEEF;
public long l956 = 0xDEADBEEF;
public long l957 = 0xDEADBEEF;
public long l958 = 0xDEADBEEF;
public long l959 = 0xDEADBEEF;
public long l960 = 0xDEADBEEF;
public long l961 = 0xDEADBEEF;
public long l962 = 0xDEADBEEF;
public long l963 = 0xDEADBEEF;
public long l964 = 0xDEADBEEF;
public long l965 = 0xDEADBEEF;
public long l966 = 0xDEADBEEF;
public long l967 = 0xDEADBEEF;
public long l968 = 0xDEADBEEF;
public long l969 = 0xDEADBEEF;
public long l970 = 0xDEADBEEF;
public long l971 = 0xDEADBEEF;
public long l972 = 0xDEADBEEF;
public long l973 = 0xDEADBEEF;
public long l974 = 0xDEADBEEF;
public long l975 = 0xDEADBEEF;
public long l976 = 0xDEADBEEF;
public long l977 = 0xDEADBEEF;
public long l978 = 0xDEADBEEF;
public long l979 = 0xDEADBEEF;
public long l980 = 0xDEADBEEF;
public long l981 = 0xDEADBEEF;
public long l982 = 0xDEADBEEF;
public long l983 = 0xDEADBEEF;
public long l984 = 0xDEADBEEF;
public long l985 = 0xDEADBEEF;
public long l986 = 0xDEADBEEF;
public long l987 = 0xDEADBEEF;
public long l988 = 0xDEADBEEF;
public long l989 = 0xDEADBEEF;
public long l990 = 0xDEADBEEF;
public long l991 = 0xDEADBEEF;
public long l992 = 0xDEADBEEF;
public long l993 = 0xDEADBEEF;
public long l994 = 0xDEADBEEF;
public long l995 = 0xDEADBEEF;
public long l996 = 0xDEADBEEF;
public long l997 = 0xDEADBEEF;
public long l998 = 0xDEADBEEF;
public long l999 = 0xDEADBEEF;
}
| 6,371 |
0 | Create_ds/heap-dump-tool/src/test/java/com/paypal/heapdumptool | Create_ds/heap-dump-tool/src/test/java/com/paypal/heapdumptool/hserr/SanitizeHserrCommandProcessorTest.java | package com.paypal.heapdumptool.hserr;
import com.paypal.heapdumptool.fixture.ResourceTool;
import com.paypal.heapdumptool.sanitizer.SanitizeStreamFactory;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.file.Paths;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
public class SanitizeHserrCommandProcessorTest {
private final SanitizeHserrCommand command = new SanitizeHserrCommand();
private final SanitizeStreamFactory streamFactory = mock(SanitizeStreamFactory.class);
private final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
private SanitizeHserrCommandProcessor processor;
@BeforeEach
public void beforeEach() throws IOException {
final String input = ResourceTool.contentOf(SanitizeHserrCommandProcessorTest.class, "hs_err_pid123.txt");
doReturn(new ByteArrayInputStream(input.getBytes(UTF_8)))
.when(streamFactory)
.newInputStream();
doReturn(outputStream).when(streamFactory).newOutputStream();
command.setInputFile(Paths.get("input"));
command.setOutputFile(Paths.get("output"));
processor = new SanitizeHserrCommandProcessor(command, streamFactory);
}
@Test
public void testProcess() throws Exception {
processor.process();
final String output = outputStream.toString(UTF_8.name());
assertThat(output)
.contains("# SIGSEGV (0xb) at pc=0x00007fab2dfe7a6d, pid=32369, tid=32375")
.doesNotContain("LANG=en_US.UTF-8")
.contains("LANG=****");
}
}
| 6,372 |
0 | Create_ds/heap-dump-tool/src/test/java/com/paypal/heapdumptool | Create_ds/heap-dump-tool/src/test/java/com/paypal/heapdumptool/hserr/SanitizeHserrCommandTest.java | package com.paypal.heapdumptool.hserr;
import org.junit.jupiter.api.Test;
import org.meanbean.test.BeanVerifier;
import static org.assertj.core.api.Assertions.assertThat;
public class SanitizeHserrCommandTest {
@Test
public void testBean() {
BeanVerifier.forClass(SanitizeHserrCommand.class)
.verifyGettersAndSetters()
.verifyToString();
assertThat(new SanitizeHserrCommand().getProcessorClass())
.isEqualTo(SanitizeHserrCommandProcessor.class);
}
}
| 6,373 |
0 | Create_ds/heap-dump-tool/src/test/java/com/paypal/heapdumptool | Create_ds/heap-dump-tool/src/test/java/com/paypal/heapdumptool/utils/ProgressMonitorTest.java | package com.paypal.heapdumptool.utils;
import org.apache.commons.io.IOUtils;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.test.system.CapturedOutput;
import org.springframework.boot.test.system.OutputCaptureExtension;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import static com.paypal.heapdumptool.sanitizer.DataSize.ofBytes;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.doCallRealMethod;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
@ExtendWith(OutputCaptureExtension.class)
public class ProgressMonitorTest {
private static final Logger LOGGER = LoggerFactory.getLogger(ProgressMonitorTest.class);
@Test
public void testNumBytesWrittenMonitor(final CapturedOutput output) {
final ProgressMonitor numBytesWrittenMonitor = ProgressMonitor.numBytesProcessedMonitor(ofBytes(5), LOGGER);
numBytesWrittenMonitor.accept(4L);
assertThat(output)
.isEmpty();
numBytesWrittenMonitor.accept(5L);
assertThat(output)
.hasLineCount(1)
.contains("Processed 5 bytes");
numBytesWrittenMonitor.accept(6L);
assertThat(output)
.hasLineCount(1)
.contains("Processed 5 bytes");
numBytesWrittenMonitor.accept(11L);
assertThat(output)
.hasLineCount(2)
.contains("Processed 5 bytes")
.contains("Processed 11 bytes");
}
@Test
public void testMonitoredInputStream() throws IOException {
final ProgressMonitor monitor = mock(ProgressMonitor.class);
final InputStream inputStream = new ByteArrayInputStream("hello".getBytes(UTF_8));
doCallRealMethod().when(monitor).monitoredInputStream(inputStream);
final InputStream monitoredInputStream = monitor.monitoredInputStream(inputStream);
IOUtils.toByteArray(monitoredInputStream);
verify(monitor, times(2)).accept((long) "hello".length());
}
@Test
public void testMonitoredOutputStream() throws IOException {
final ProgressMonitor monitor = mock(ProgressMonitor.class);
final OutputStream outputStream = new ByteArrayOutputStream();
doCallRealMethod().when(monitor).monitoredOutputStream(outputStream);
final OutputStream monitoredOutputStream = monitor.monitoredOutputStream(outputStream);
IOUtils.write("world", monitoredOutputStream, UTF_8);
verify(monitor).accept((long) "world".length());
}
}
| 6,374 |
0 | Create_ds/heap-dump-tool/src/test/java/com/paypal/heapdumptool | Create_ds/heap-dump-tool/src/test/java/com/paypal/heapdumptool/utils/DateTimeToolTest.java | package com.paypal.heapdumptool.utils;
import org.junit.jupiter.api.Test;
import java.time.Instant;
import static com.paypal.heapdumptool.utils.DateTimeTool.getFriendlyDuration;
import static org.assertj.core.api.Assertions.assertThat;
public class DateTimeToolTest {
@Test
public void testFriendlyDuration() {
final Instant start = Instant.now().minusSeconds(65);
assertThat(getFriendlyDuration(start))
.satisfiesAnyOf(display -> assertThat(display).isEqualTo("1m5s"),
display -> assertThat(display).isEqualTo("1m6s"));
}
}
| 6,375 |
0 | Create_ds/heap-dump-tool/src/test/java/com/paypal/heapdumptool | Create_ds/heap-dump-tool/src/test/java/com/paypal/heapdumptool/utils/ProcessToolTest.java | package com.paypal.heapdumptool.utils;
import com.paypal.heapdumptool.fixture.ConstructorTester;
import com.paypal.heapdumptool.utils.ProcessTool.ProcessResult;
import org.apache.commons.io.input.BrokenInputStream;
import org.junit.jupiter.api.Test;
import java.io.UncheckedIOException;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
public class ProcessToolTest {
@Test
public void testRun() throws Exception {
final ProcessResult result = ProcessTool.run("ls", "-l");
assertThat(result.exitCode).isEqualTo(0);
assertThat(result.stdout).isNotEmpty();
assertThat(result.stderr).isEmpty();
assertThat(result.stdoutLines()).isNotEmpty();
}
@Test
public void testBrokenInputStream() {
assertThatCode(() -> ProcessTool.readStream(new BrokenInputStream()))
.isInstanceOf(UncheckedIOException.class);
}
@Test
public void testConstructor() throws Exception {
ConstructorTester.test(ProcessTool.class);
}
}
| 6,376 |
0 | Create_ds/heap-dump-tool/src/test/java/com/paypal/heapdumptool | Create_ds/heap-dump-tool/src/test/java/com/paypal/heapdumptool/utils/CallableToolTest.java | package com.paypal.heapdumptool.utils;
import com.paypal.heapdumptool.fixture.ConstructorTester;
import org.junit.jupiter.api.DynamicTest;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestFactory;
import static com.paypal.heapdumptool.utils.CallableTool.callQuietlyWithDefault;
import static java.util.Objects.requireNonNull;
import static org.assertj.core.api.Assertions.assertThat;
public class CallableToolTest {
@TestFactory
public DynamicTest[] callQuietlyWithDefaultTests() {
return new DynamicTest[] {
DynamicTest.dynamicTest("Happy Path", () -> {
final int result = callQuietlyWithDefault(5, () -> 1);
assertThat(result).isEqualTo(1);
}),
DynamicTest.dynamicTest("Unhappy Path", () -> {
final int result = callQuietlyWithDefault(5, () -> requireNonNull(null));
assertThat(result).isEqualTo(5);
}),
};
}
@Test
public void testConstructor() throws Exception {
ConstructorTester.test(CallableTool.class);
}
}
| 6,377 |
0 | Create_ds/heap-dump-tool/src/test/java/com/paypal/heapdumptool | Create_ds/heap-dump-tool/src/test/java/com/paypal/heapdumptool/cli/CliBootstrapTest.java | package com.paypal.heapdumptool.cli;
import com.paypal.heapdumptool.fixture.ConstructorTester;
import org.apache.commons.lang3.reflect.ConstructorUtils;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.MockedStatic;
import java.lang.reflect.InvocationTargetException;
import static com.paypal.heapdumptool.fixture.MockitoTool.genericMock;
import static org.apache.commons.lang3.reflect.ConstructorUtils.invokeConstructor;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.mockStatic;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
public class CliBootstrapTest {
private final CliCommand command = mock(CliCommand.class);
private final CliCommandProcessor processor = genericMock(CliCommandProcessor.class);
@BeforeEach
public void beforeEach() {
doReturn(processor.getClass())
.when(command)
.getProcessorClass();
}
@Test
public void testRunCommand() throws Exception {
try (final MockedStatic<ConstructorUtils> mocked = mockStatic(ConstructorUtils.class)) {
mocked.when(() -> invokeConstructor(processor.getClass(), command))
.thenReturn(processor);
CliBootstrap.runCommand(command);
verify(processor).process();
}
}
@Test
public void testRunCommandInvocationTargetException() throws Exception {
try (final MockedStatic<ConstructorUtils> mocked = mockStatic(ConstructorUtils.class)) {
mocked.when(() -> invokeConstructor(processor.getClass(), command))
.thenThrow(new InvocationTargetException(new IllegalStateException()));
verifyExceptionThrown();
}
}
@Test
public void testRunCommandException() throws Exception {
try (final MockedStatic<ConstructorUtils> mocked = mockStatic(ConstructorUtils.class)) {
mocked.when(() -> invokeConstructor(processor.getClass(), command))
.thenThrow(new IllegalStateException());
final Throwable throwable = catchThrowable(() -> CliBootstrap.runCommand(command));
assertThat(throwable).isInstanceOf(IllegalStateException.class);
verify(processor, never()).process();
}
}
private void verifyExceptionThrown() throws Exception {
final Throwable throwable = catchThrowable(() -> CliBootstrap.runCommand(command));
assertThat(throwable).isInstanceOf(IllegalStateException.class);
verify(processor, never()).process();
}
@Test
public void testConstructor() throws Exception {
ConstructorTester.test(CliBootstrap.class);
}
}
| 6,378 |
0 | Create_ds/heap-dump-tool/src/test/java/com/paypal/heapdumptool | Create_ds/heap-dump-tool/src/test/java/com/paypal/heapdumptool/cli/CliCommandTest.java | package com.paypal.heapdumptool.cli;
import org.junit.jupiter.api.Test;
import org.mockito.MockedStatic;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doCallRealMethod;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.mockStatic;
public class CliCommandTest {
@Test
public void testCall() throws Exception {
final CliCommand command = mock(CliCommand.class);
doCallRealMethod()
.when(command)
.call();
try (final MockedStatic<CliBootstrap> mocked = mockStatic(CliBootstrap.class)) {
command.call();
mocked.verify(() -> CliBootstrap.runCommand(any()));
}
}
}
| 6,379 |
0 | Create_ds/heap-dump-tool/src/main/java/com/paypal | Create_ds/heap-dump-tool/src/main/java/com/paypal/heapdumptool/Application.java | package com.paypal.heapdumptool;
import com.paypal.heapdumptool.Application.VersionProvider;
import com.paypal.heapdumptool.capture.CaptureCommand;
import com.paypal.heapdumptool.capture.PrivilegeEscalator.Escalation;
import com.paypal.heapdumptool.hserr.SanitizeHserrCommand;
import com.paypal.heapdumptool.sanitizer.DataSize;
import com.paypal.heapdumptool.sanitizer.SanitizeCommand;
import org.apache.commons.text.StringSubstitutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import picocli.CommandLine;
import picocli.CommandLine.Command;
import picocli.CommandLine.HelpCommand;
import picocli.CommandLine.IVersionProvider;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Properties;
import static com.paypal.heapdumptool.Application.APP_ID;
import static com.paypal.heapdumptool.capture.PrivilegeEscalator.escalatePrivilegesIfNeeded;
import static com.paypal.heapdumptool.capture.PrivilegeEscalator.Escalation.ESCALATED;
import static org.apache.commons.io.IOUtils.resourceToByteArray;
@Command(name = APP_ID,
description = "Tool primarily for capturing or sanitizing heap dumps",
mixinStandardHelpOptions = true,
versionProvider = VersionProvider.class,
subcommands = {
CaptureCommand.class,
SanitizeCommand.class,
SanitizeHserrCommand.class,
HelpCommand.class,
}
)
public class Application {
public static final String APP_ID = "heap-dump-tool";
// Stay with "String[] args". vararg "String... args" causes weird failure with mockito in Java 11
public static void main(final String[] args) throws Exception {
final Escalation escalation = escalatePrivilegesIfNeeded(args);
if (escalation == ESCALATED) {
return;
}
final CommandLine commandLine = new CommandLine(new Application());
commandLine.setUsageHelpWidth(120);
commandLine.registerConverter(DataSize.class, DataSize::parse);
commandLine.setAbbreviatedOptionsAllowed(true);
final int exitCode = commandLine.execute(args);
systemExit(exitCode);
}
// for mocking
static void systemExit(final int exitCode) {
System.exit(exitCode);
}
public static class VersionProvider implements IVersionProvider {
public static void printVersion() throws IOException {
final String[] versionInfo = new VersionProvider().getVersion();
final Logger logger = LoggerFactory.getLogger(Application.class); // lazy init
logger.info(versionInfo[0]);
}
@Override
public String[] getVersion() throws IOException {
final byte[] bytes = resourceToByteArray("/git-heap-dump-tool.properties");
final Properties gitProperties = new Properties();
gitProperties.load(new ByteArrayInputStream(bytes));
gitProperties.put("appId", APP_ID);
final String versionInfo = StringSubstitutor.replace(
"${appId} (${git.build.version} ${git.commit.id.abbrev}, ${git.commit.time})",
gitProperties);
return new String[] {versionInfo};
}
}
}
| 6,380 |
0 | Create_ds/heap-dump-tool/src/main/java/com/paypal/heapdumptool | Create_ds/heap-dump-tool/src/main/java/com/paypal/heapdumptool/capture/CaptureStreamFactory.java | package com.paypal.heapdumptool.capture;
import com.paypal.heapdumptool.sanitizer.SanitizeCommand;
import com.paypal.heapdumptool.sanitizer.SanitizeStreamFactory;
import org.apache.commons.io.output.CloseShieldOutputStream;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Path;
import java.util.concurrent.atomic.AtomicReference;
import static java.util.Objects.requireNonNull;
import static org.apache.commons.compress.utils.IOUtils.closeQuietly;
public class CaptureStreamFactory extends SanitizeStreamFactory implements Closeable {
private final AtomicReference<InputStream> inputStreamRef;
private final AtomicReference<OutputStream> outputStreamRef;
public CaptureStreamFactory(final SanitizeCommand command, final InputStream inputStream) {
super(command);
this.inputStreamRef = new AtomicReference<>(inputStream);
this.outputStreamRef = new AtomicReference<>();
}
@Override
protected InputStream newInputStream(final Path ignored) {
return requireNonNull(inputStreamRef.getAndSet(null));
}
@Override
public OutputStream newOutputStream() throws IOException {
final OutputStream stream = super.newOutputStream();
outputStreamRef.compareAndSet(null, stream);
return CloseShieldOutputStream.wrap(stream);
}
public OutputStream getNativeOutputStream() {
return outputStreamRef.get();
}
@Override
public void close() {
closeQuietly(getNativeOutputStream());
}
}
| 6,381 |
0 | Create_ds/heap-dump-tool/src/main/java/com/paypal/heapdumptool | Create_ds/heap-dump-tool/src/main/java/com/paypal/heapdumptool/capture/PrivilegeEscalator.java | package com.paypal.heapdumptool.capture;
import com.paypal.heapdumptool.utils.ProcessTool;
import com.paypal.heapdumptool.utils.ProcessTool.ProcessResult;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.text.StringSubstitutor;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.Callable;
import java.util.stream.Stream;
import static com.paypal.heapdumptool.capture.CaptureCommand.DOCKER_REGISTRY_OPTION;
import static com.paypal.heapdumptool.capture.PrivilegeEscalator.Escalation.ESCALATED;
import static com.paypal.heapdumptool.capture.PrivilegeEscalator.Escalation.PRIVILEGED_ALREADY;
import static com.paypal.heapdumptool.utils.CallableTool.callQuietlyWithDefault;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.stream.Collectors.joining;
import static org.apache.commons.io.IOUtils.resourceToString;
/**
* Makes it possible to run docker inside docker. Prints a "docker run" command which the user can execute so that the container
* has the right flags (--privileged and --pid) set.
*/
public class PrivilegeEscalator {
public static final String DEFAULT_REGISTRY = System.getProperty("hdt.default-registry", "index.docker.io");
public static final String IMAGE_NAME = System.getProperty("hdt.image-name", "heapdumptool/heapdumptool");
private static final String DOCKER = "docker";
public static Escalation escalatePrivilegesIfNeeded(final String... args) throws Exception {
if (!isInDockerContainer() || isLikelyPrivileged()) {
return PRIVILEGED_ALREADY;
}
final String shellTemplate = resourceToString("/privilege-escalate.sh.tmpl", UTF_8);
final Map<String, String> templateParams = buildTemplateParams(args);
final String shellCode = StringSubstitutor.replace(shellTemplate, templateParams, "__", "__");
println(shellCode);
return ESCALATED;
}
public static enum Escalation {
ESCALATED,
PRIVILEGED_ALREADY
}
public static boolean isInDockerContainer() {
final Path file = Paths.get("/proc/1/cgroup");
final Callable<Boolean> cgroupContainsDocker = () -> Files.readAllLines(file)
.stream()
.anyMatch(line -> line.contains(DOCKER));
final boolean isInContainer = callQuietlyWithDefault(false, cgroupContainsDocker);
if (!isInContainer) {
// If true, then definitely true.
// If false, then process might be running on the host, or be in a privileged container with pid namespace mounted.
// Just try running nsenter1 docker then
final int exitCode = callQuietlyWithDefault(1, () -> ProcessTool.run("nsenter1", DOCKER).exitCode);
return exitCode == 0;
}
return isInContainer;
}
// yes, print directly to stdout (bypassing SysOutOverSLF4J or other logger decorations)
static void println(final String str) {
System.out.println(str);
}
private static boolean isLikelyPrivileged() {
final Callable<Boolean> canRunDockerInsideDocker = () -> {
final Path nsenter1 = Paths.get("nsenter1");
final ProcessResult result = ProcessTool.run(nsenter1.toString(), DOCKER);
return result.exitCode == 0;
};
return callQuietlyWithDefault(false, canRunDockerInsideDocker);
}
private static Map<String, String> buildTemplateParams(final String... args) {
final String quotedArgs = Stream.of(args)
.map(PrivilegeEscalator::quoteIfNeeded)
.collect(joining(" "));
final Optional<String> forcedDockerRegistry = findForcedDockerRegistry(args);
final String defaultRegistry = forcedDockerRegistry.orElse(DEFAULT_REGISTRY);
final String dockerRegistryEnvName = forcedDockerRegistry.isPresent()
? "FORCED_DOCKER_REGISTRY"
: "DOCKER_REGISTRY";
final Map<String, String> params = new HashMap<>();
params.put("IMAGE_NAME", IMAGE_NAME);
params.put("ARGS", quotedArgs);
params.put("DEFAULT_REGISTRY", defaultRegistry);
params.put("DOCKER_REGISTRY_ENV_NAME", dockerRegistryEnvName);
return params;
}
private static Optional<String> findForcedDockerRegistry(final String... args) {
String forcedDockerRegistry = null;
for (int i = 0; i < args.length; i++) {
final String arg = args[i];
if (arg.startsWith(DOCKER_REGISTRY_OPTION)) {
if (arg.contains("=")) {
forcedDockerRegistry = StringUtils.substringAfterLast(arg, "=");
break;
}
if (i < args.length - 1) {
forcedDockerRegistry = args[i + 1];
break;
}
throw new IllegalArgumentException("Cannot find argument value for " + DOCKER_REGISTRY_OPTION);
}
}
return Optional.ofNullable(forcedDockerRegistry);
}
private static String quoteIfNeeded(final String str) {
return str.contains(" ")
? "\"" + str + "\""
: str;
}
private PrivilegeEscalator() {
throw new AssertionError();
}
}
| 6,382 |
0 | Create_ds/heap-dump-tool/src/main/java/com/paypal/heapdumptool | Create_ds/heap-dump-tool/src/main/java/com/paypal/heapdumptool/capture/CaptureCommandProcessor.java | package com.paypal.heapdumptool.capture;
import com.paypal.heapdumptool.cli.CliCommandProcessor;
import com.paypal.heapdumptool.sanitizer.SanitizeCommand;
import com.paypal.heapdumptool.sanitizer.SanitizeCommandProcessor;
import com.paypal.heapdumptool.utils.ProcessTool;
import com.paypal.heapdumptool.utils.ProcessTool.ProcessResult;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;
import org.apache.commons.lang3.function.Failable;
import org.apache.commons.text.StringSubstitutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.Closeable;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.PosixFilePermission;
import java.time.Instant;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import static com.paypal.heapdumptool.utils.DateTimeTool.getFriendlyDuration;
import static com.paypal.heapdumptool.utils.ProcessTool.processBuilder;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.time.Instant.now;
import static org.apache.commons.lang3.StringUtils.substringAfterLast;
import static org.apache.commons.lang3.StringUtils.substringBefore;
public class CaptureCommandProcessor implements CliCommandProcessor {
private static final String DOCKER = "docker";
private static final Logger LOGGER = LoggerFactory.getLogger(CaptureCommandProcessor.class);
private final CaptureCommand command;
private final boolean isInContainer;
public CaptureCommandProcessor(final CaptureCommand command) {
this.command = command;
this.isInContainer = PrivilegeEscalator.isInDockerContainer();
}
@Override
public void process() throws Exception {
final Instant now = now();
LOGGER.info("Capturing sanitized heap dump. container={}", command.getContainerName());
validateContainerRunning();
final long pid = findPidInAppContainer();
final Path inputHeapDumpFile = createPlainHeapDumpInAppContainer(pid);
final String threadDump = captureThreadDump(pid);
final Path output;
try (final InputStream inputStream = createCopyStreamOutOfAppContainer(inputHeapDumpFile)) {
output = sanitizeHeapDump(inputHeapDumpFile, inputStream, threadDump);
} finally {
deletePlainHeapDumpInAppContainer(inputHeapDumpFile);
}
LOGGER.info("Captured sanitized heap dump in {}. Output: {}", getFriendlyDuration(now), output);
}
private String captureThreadDump(final long pid) throws Exception {
final ProcessResult result = execInAppContainer("jcmd", pid, "Thread.print", "-l");
return result.stdout;
}
private Path sanitizeHeapDump(final Path filePath, final InputStream inputStream, final String threadDump) throws Exception {
final String destFile = filePath.getFileName().toAbsolutePath() // re-eval filename in current cwd
+ ".zip";
final Path destFilePath = Paths.get(destFile);
final SanitizeCommand sanitizeCommand = new SanitizeCommand();
sanitizeCommand.setInputFile(filePath); // not used. for display only
sanitizeCommand.setOutputFile(destFilePath);
sanitizeCommand.setBufferSize(command.getBufferSize());
sanitizeCommand.setTarInput(true);
sanitizeCommand.setZipOutput(true);
try (final CaptureStreamFactory captureStreamFactory = new CaptureStreamFactory(sanitizeCommand, inputStream)) {
final SanitizeCommandProcessor processor = SanitizeCommandProcessor.newInstance(sanitizeCommand, captureStreamFactory);
processor.process();
writeThreadDump(threadDump, filePath, captureStreamFactory);
}
updateFilePermissions(destFilePath);
return destFilePath;
}
private void writeThreadDump(final String threadDump, final Path filePath, final CaptureStreamFactory captureStreamFactory) throws Exception {
final ZipOutputStream zipStream = (ZipOutputStream) captureStreamFactory.getNativeOutputStream();
final String fileName = filePath.getFileName()
.toString()
.replace(".hprof", ".threads.txt");
Validate.validState(fileName.endsWith(".threads.txt"));
zipStream.putNextEntry(new ZipEntry(fileName));
IOUtils.write(threadDump, zipStream, UTF_8);
}
private void updateFilePermissions(final Path destFilePath) throws Exception {
Files.setPosixFilePermissions(destFilePath, globalReadWritePermissions());
final String hostUser = System.getProperty("hdt.HOST_USER", System.getenv("HOST_USER"));
if (hostUser != null) {
invokePrivilegedProcess("chown", hostUser + ":" + hostUser, destFilePath.toString());
}
}
private Set<PosixFilePermission> globalReadWritePermissions() {
return Stream.of(PosixFilePermission.values())
.filter(permission -> !permission.name().contains("EXECUTE"))
.collect(Collectors.toSet());
}
private InputStream createCopyStreamOutOfAppContainer(final Path filePath) throws IOException {
final String src = command.getContainerName() + ":" + filePath;
final String[] args = array(DOCKER, "cp", src, "-");
logProcessArgs(args);
final String[] cmd = nsenterIfNeeded(args);
final Process process = processBuilder(cmd).start();
closeQuietly(process.getOutputStream());
closeQuietly(process.getErrorStream());
return new FilterInputStream(process.getInputStream()) {
@Override
public void close() throws IOException {
super.close();
process.destroy();
}
};
}
private void deletePlainHeapDumpInAppContainer(final Path filePath) throws Exception {
execInAppContainer("rm", filePath);
}
private long findPidInAppContainer() {
if (command.getPid() != null) {
return command.getPid();
}
final ProcessResult result = Failable.call(() -> execInAppContainer("jps"));
final Stream<String> javaProcesses = result.stdoutLines()
.stream()
.map(String::trim)
.filter(StringUtils::isNotEmpty)
.filter(line -> !substringAfterLast(line, " ").equals("Jps"));
final long[] pids = javaProcesses.map(line -> substringBefore(line, " "))
.mapToLong(Long::parseLong)
.toArray();
Validate.validState(pids.length == 1, "Cannot find unique Java process. container=%s found=%s", command.getContainerName(), Arrays.toString(pids));
return pids[0];
}
private Path createPlainHeapDumpInAppContainer(final long pid) throws Exception {
final Path filePath = newHeapDumpFilePath();
final ProcessResult result = execInAppContainer("jcmd", pid, "GC.heap_dump", filePath);
Validate.validState(result.stdout.contains("Heap dump file created"),
"Cannot create heap dump. container=%s pid=%s"
+ "\nstdout=%s"
+ "\nstderr=%s",
command.getContainerName(),
pid,
result.stdout,
result.stderr);
return filePath;
}
private Path newHeapDumpFilePath() {
final Map<String, String> props = new HashMap<>();
props.put("containerName", command.getContainerName());
props.put("timestamp", Instant.now().toString().replace(":", "-"));
final String fileName = StringSubstitutor.replace("${containerName}-${timestamp}.hprof", props);
return Paths.get("/tmp/", fileName);
}
private void validateContainerRunning() throws Exception {
final ProcessResult result = invokePrivilegedProcess(DOCKER, "ps", "--filter", "name=" + command.getContainerName());
result.stdoutLines()
.stream()
.skip(1)
.map(String::trim)
.filter(StringUtils::isNotEmpty)
.filter(line -> {
final String actualContainerName = substringAfterLast(line, " ");
return actualContainerName.equals(command.getContainerName());
})
.findFirst()
.orElseThrow(() -> new IllegalArgumentException("Cannot find container. name=" + command.getContainerName()));
}
private ProcessResult execInAppContainer(final Object... args) throws Exception {
final String[] stringArgs = Stream.of(args)
.map(String::valueOf)
.toArray(String[]::new);
final String[] cmd = concat(array(DOCKER, "exec", command.getContainerName()),
stringArgs);
return invokePrivilegedProcess(cmd);
}
private String[] nsenterIfNeeded(final String... args) {
if (!isInContainer) {
return args;
}
return concat("nsenter1", args);
}
private ProcessResult invokePrivilegedProcess(final String... args) throws Exception {
logProcessArgs(args);
final String[] cmd = nsenterIfNeeded(args);
return ProcessTool.run(cmd);
}
private void logProcessArgs(final String... cmd) {
if (LOGGER.isInfoEnabled()) {
LOGGER.info("Running: {}", String.join(" ", cmd));
}
}
private static <T> T[] concat(final T element, final T[] array) {
return ArrayUtils.addFirst(array, element);
}
private static <T> T[] concat(final T[] element, final T[] array) {
return ArrayUtils.addAll(element, array);
}
private static String[] array(final String... elements) {
return elements;
}
private static void closeQuietly(final Closeable closeable) {
IOUtils.closeQuietly(closeable);
}
}
| 6,383 |
0 | Create_ds/heap-dump-tool/src/main/java/com/paypal/heapdumptool | Create_ds/heap-dump-tool/src/main/java/com/paypal/heapdumptool/capture/CaptureCommand.java | package com.paypal.heapdumptool.capture;
import com.paypal.heapdumptool.cli.CliCommand;
import com.paypal.heapdumptool.sanitizer.DataSize;
import org.apache.commons.text.StringEscapeUtils;
import picocli.CommandLine.Command;
import picocli.CommandLine.Option;
import picocli.CommandLine.Parameters;
import static com.paypal.heapdumptool.sanitizer.DataSize.ofMegabytes;
import static org.apache.commons.lang3.builder.ToStringBuilder.reflectionToString;
import static org.apache.commons.lang3.builder.ToStringStyle.MULTI_LINE_STYLE;
import static picocli.CommandLine.Help.Visibility.ALWAYS;
@Command(name = "capture",
description = {
"Capture sanitized heap dump of a containerized app",
"Plain thread dump is also captured"
},
abbreviateSynopsis = true)
public class CaptureCommand implements CliCommand {
static final String DOCKER_REGISTRY_OPTION = "--docker-registry";
// to allow field injection from picocli, these variables can't be final
@Parameters(index = "0", description = "Container name")
private String containerName;
@Option(names = { "-p", "--pid" }, description = "Pid within the container, if there are multiple Java processes")
private Long pid;
@Option(names = { "-d", DOCKER_REGISTRY_OPTION }, description = "docker registry hostname for bootstrapping heap-dump-tool docker image")
private String dockerRegistry;
@Option(names = { "-z", "--zip-output" }, description = "Write zipped output", defaultValue = "true", showDefaultValue = ALWAYS)
private boolean zipOutput = true;
@Option(names = { "-t", "--text" }, description = "Sanitization text to replace with", defaultValue = "\\0", showDefaultValue = ALWAYS)
private String sanitizationText = "\\0";
@Option(names = { "-s", "--sanitize-byte-char-arrays-only" }, description = "Sanitize byte/char arrays only", defaultValue = "true", showDefaultValue = ALWAYS)
private boolean sanitizeByteCharArraysOnly = true;
@Option(names = { "-b", "--buffer-size" }, description = "Buffer size for reading and writing", defaultValue = "100MB", showDefaultValue = ALWAYS)
private DataSize bufferSize = ofMegabytes(100);
@Override
public Class<CaptureCommandProcessor> getProcessorClass() {
return CaptureCommandProcessor.class;
}
public DataSize getBufferSize() {
return bufferSize;
}
public void setBufferSize(final DataSize bufferSize) {
this.bufferSize = bufferSize;
}
public String getContainerName() {
return containerName;
}
public void setContainerName(final String containerName) {
this.containerName = containerName;
}
public Long getPid() {
return pid;
}
public void setPid(final Long pid) {
this.pid = pid;
}
public boolean isZipOutput() {
return zipOutput;
}
public void setZipOutput(final boolean zipOutput) {
this.zipOutput = zipOutput;
}
public boolean isSanitizeByteCharArraysOnly() {
return sanitizeByteCharArraysOnly;
}
public void setSanitizeByteCharArraysOnly(final boolean sanitizeByteCharArraysOnly) {
this.sanitizeByteCharArraysOnly = sanitizeByteCharArraysOnly;
}
public String getSanitizationText() {
return StringEscapeUtils.unescapeJava(sanitizationText);
}
public void setSanitizationText(final String sanitizationText) {
// e.g. unescape user-supplied \\0 string (2 chars) to \0 string (1 char)
this.sanitizationText = StringEscapeUtils.unescapeJava(sanitizationText);
}
@Override
public String toString() {
return reflectionToString(this, MULTI_LINE_STYLE);
}
}
| 6,384 |
0 | Create_ds/heap-dump-tool/src/main/java/com/paypal/heapdumptool | Create_ds/heap-dump-tool/src/main/java/com/paypal/heapdumptool/sanitizer/SanitizeCommandProcessor.java | package com.paypal.heapdumptool.sanitizer;
import com.paypal.heapdumptool.cli.CliCommandProcessor;
import org.apache.commons.lang3.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.InputStream;
import java.io.OutputStream;
import java.time.Instant;
import static com.paypal.heapdumptool.utils.DateTimeTool.getFriendlyDuration;
import static com.paypal.heapdumptool.utils.ProgressMonitor.numBytesProcessedMonitor;
public class SanitizeCommandProcessor implements CliCommandProcessor {
private static final Logger LOGGER = LoggerFactory.getLogger(SanitizeCommandProcessor.class);
private final SanitizeCommand command;
private final SanitizeStreamFactory streamFactory;
// for mocking
public static SanitizeCommandProcessor newInstance(final SanitizeCommand command, final SanitizeStreamFactory streamFactory) {
return new SanitizeCommandProcessor(command, streamFactory);
}
public SanitizeCommandProcessor(final SanitizeCommand command) {
this(command, new SanitizeStreamFactory(command));
}
public SanitizeCommandProcessor(final SanitizeCommand command, final SanitizeStreamFactory streamFactory) {
Validate.isTrue(command.getBufferSize().toBytes() >= 0, "Invalid buffer size");
this.command = command;
this.streamFactory = streamFactory;
}
@Override
public void process() throws Exception {
LOGGER.info("Starting heap dump sanitization");
LOGGER.info("Input File: {}", command.getInputFile());
LOGGER.info("Output File: {}", command.getOutputFile());
final Instant now = Instant.now();
try (final InputStream inputStream = streamFactory.newInputStream();
final OutputStream outputStream = streamFactory.newOutputStream()) {
final HeapDumpSanitizer sanitizer = new HeapDumpSanitizer();
sanitizer.setInputStream(inputStream);
sanitizer.setOutputStream(outputStream);
sanitizer.setProgressMonitor(numBytesProcessedMonitor(command.getBufferSize(), LOGGER));
sanitizer.setSanitizationText(command.getSanitizationText());
sanitizer.setSanitizeByteCharArraysOnly(command.isSanitizeByteCharArraysOnly());
sanitizer.setSanitizeArraysOnly(command.isSanitizeArraysOnly());
sanitizer.sanitize();
}
LOGGER.info("Finished heap dump sanitization in {}", getFriendlyDuration(now));
}
}
| 6,385 |
0 | Create_ds/heap-dump-tool/src/main/java/com/paypal/heapdumptool | Create_ds/heap-dump-tool/src/main/java/com/paypal/heapdumptool/sanitizer/HeapDumpSanitizer.java | package com.paypal.heapdumptool.sanitizer;
import com.paypal.heapdumptool.utils.ProgressMonitor;
import org.apache.commons.io.input.InfiniteCircularInputStream;
import org.apache.commons.lang3.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Optional;
import static org.apache.commons.lang3.BooleanUtils.isFalse;
/**
* Heavily based on: <br>
*
* <a href="http://hg.openjdk.java.net/jdk6/jdk6/jdk/raw-file/tip/src/share/demo/jvmti/hprof/manual.html#mozTocId848088">
* Heap Dump Binary Format Spec
* </a> (highly recommended to make sense of the code in any meaningful way)
* <br>
*
* <a href="https://github.com/openjdk/jdk/blob/a2bbf933d96dc4a911ac4b429519937d8dd83200/src/hotspot/share/services/heapDumper.cpp">
* JDK heapDumper.cpp
* </a>
* <br>
*
* <a href="https://github.com/AdoptOpenJDK/jheappo">
* JHeappo
* </a> (clean modern code)
* <br>
*
* <a href="https://github.com/apache/netbeans/tree/f2611e358c181935500ea4d9d9142fb850504a72/profiler/lib.profiler/src/org/netbeans/lib/profiler/heap">
* NetBeans/VisualVM HeapDump code (old but reference)
* </a>
*/
public class HeapDumpSanitizer {
private static final int TAG_HEAP_DUMP = 0x0C;
private static final int TAG_HEAP_DUMP_SEGMENT = 0x1C;
private static final Logger LOGGER = LoggerFactory.getLogger(HeapDumpSanitizer.class);
// for debugging/testing
private static final boolean enableSanitization = isFalse(Boolean.getBoolean("disable-sanitization"));
private InputStream inputStream;
private OutputStream outputStream;
private ProgressMonitor progressMonitor;
private String sanitizationText;
private boolean sanitizeArraysOnly;
private boolean sanitizeByteCharArraysOnly;
public void setInputStream(final InputStream inputStream) {
this.inputStream = inputStream;
}
public void setOutputStream(final OutputStream outputStream) {
this.outputStream = outputStream;
}
public void setProgressMonitor(final ProgressMonitor numBytesWrittenMonitor) {
this.progressMonitor = numBytesWrittenMonitor;
}
public void setSanitizationText(final String sanitizationText) {
this.sanitizationText = sanitizationText;
}
public void setSanitizeArraysOnly(final boolean sanitizeArraysOnly) {
if (sanitizeArraysOnly && sanitizeByteCharArraysOnly) {
throw new IllegalArgumentException("sanitizeArraysOnly and sanitizeByteCharArraysOnly cannot be both set to true simultaneously");
}
this.sanitizeArraysOnly = sanitizeArraysOnly;
}
public void setSanitizeByteCharArraysOnly(final boolean sanitizeByteCharArraysOnly) {
if (sanitizeArraysOnly && sanitizeByteCharArraysOnly) {
throw new IllegalArgumentException("sanitizeArraysOnly and sanitizeByteCharArraysOnly cannot be both set to true simultaneously");
}
this.sanitizeByteCharArraysOnly = sanitizeByteCharArraysOnly;
}
public void sanitize() throws IOException {
Validate.notEmpty(sanitizationText);
final Pipe pipe = new Pipe(inputStream, outputStream, progressMonitor);
/*
* The basic fields in the binary output are u1 (1 byte), u2 (2 byte), u4 (4 byte), and u8 (8 byte).
*
* The binary output begins with the information:
* [u1]* An initial NULL terminated series of bytes representing the format name and version
* u4 size of identifiers. Identifiers are used to represent UTF8 strings, objects, stack traces, etc.
* u4 high word of number of milliseconds since 0:00 GMT, 1/1/70
* u4 low word of number of milliseconds since 0:00 GMT, 1/1/70
*/
final String version = pipe.pipeNullTerminatedString().trim();
LOGGER.debug("Heap Dump Version: {}", version);
pipe.setIdSize((int) pipe.pipeU4());
LOGGER.debug("Id Size: {}", pipe.getIdSize());
pipe.pipe(8);
/*
* Followed by a sequence of records that look like:
* u1 TAG: denoting the type of the record
* u4 TIME: number of microseconds since the time stamp in the header
* u4 LENGTH: number of bytes that follow this u4 field and belong to this record
* [u1]* BODY: as many bytes as specified in the above u4 field
*/
while (true) {
final int tag = pipe.pipeU1IfPossible();
if (tag == -1) {
break;
}
pipe.pipeU4(); // timestamp
final long length = pipe.pipeU4();
LOGGER.debug("Tag: {}", tag);
LOGGER.debug("Length: {}", length);
if (isHeapDumpRecord(tag)) {
final Pipe heapPipe = pipe.newInputBoundedPipe(length);
copyHeapDumpRecord(heapPipe);
} else {
pipe.pipe(length);
}
}
}
private void copyHeapDumpRecord(final Pipe pipe) throws IOException {
while (true) {
final int tag = pipe.pipeU1IfPossible();
if (tag == -1) {
break;
}
LOGGER.debug("Heap Dump Tag: {}", tag);
pipe.pipeId();
switch (tag) {
case 0xFF:
break;
case 0x01:
pipe.pipeId();
break;
case 0x02:
case 0x03:
pipe.pipe(4 + 4);
break;
case 0x04:
pipe.pipeU4();
break;
case 0x05:
break;
case 0x06:
pipe.pipeU4();
break;
case 0x07:
break;
case 0x08:
pipe.pipe(4 + 4);
break;
case 0x20:
copyHeapDumpClassDump(pipe, tag);
break;
case 0x21:
copyHeapDumpInstanceDump(pipe, tag);
break;
case 0x22:
copyHeapDumpObjectArrayDump(pipe, tag);
break;
case 0x23:
copyHeapDumpPrimitiveArrayDump(pipe, tag);
break;
default:
throw new IllegalArgumentException("" + tag);
}
}
}
private void copyHeapDumpClassDump(final Pipe pipe, @SuppressWarnings("unused") final int id) throws IOException {
pipe.pipeU4(); // stacktrace
pipe.pipeId(); // super class object id
pipe.pipeId(); // class loader object id
pipe.pipeId(); // signers object id
pipe.pipeId(); // protection domain
pipe.pipeId(); // reserved
pipe.pipeId(); // reserved
pipe.pipeU4(); // instance size
final int numConstantPoolRecords = pipe.pipeU2();
for (int i = 0; i < numConstantPoolRecords; i++) {
pipe.pipeU2();
final int entryType = pipe.pipeU1();
pipeBasicType(pipe, entryType);
}
final int numStaticFields = pipe.pipeU2();
for (int i = 0; i < numStaticFields; i++) {
pipe.pipeId();
final int entryType = pipe.pipeU1();
pipeStaticField(pipe, entryType);
}
final int numInstanceFields = pipe.pipeU2();
for (int i = 0; i < numInstanceFields; i++) {
pipe.pipeId();
pipe.pipeU1();
}
}
private void pipeStaticField(final Pipe pipe, final int entryType) throws IOException {
final int valueSize = BasicType.findValueSize(entryType, pipe.getIdSize());
if (enableSanitization && !sanitizeByteCharArraysOnly && !sanitizeArraysOnly) {
applySanitization(pipe, valueSize);
} else {
pipe.pipe(valueSize);
}
}
private void pipeBasicType(final Pipe pipe, final int entryType) throws IOException {
final int valueSize = BasicType.findValueSize(entryType, pipe.getIdSize());
pipe.pipe(valueSize);
}
/*
*
* INSTANCE DUMP 0x21
*
* ID object ID
* u4 stack trace serial number
* ID class object ID
* u4 number of bytes that follow
* [value]* instance field values (this class, followed by super class, etc)
*/
private void copyHeapDumpInstanceDump(final Pipe pipe, @SuppressWarnings("unused") final int id) throws IOException {
pipe.pipeU4();
pipe.pipeId();
final long numBytes = pipe.pipeU4();
if (enableSanitization && !sanitizeByteCharArraysOnly && !sanitizeArraysOnly) {
applySanitization(pipe, numBytes);
} else {
pipe.pipe(numBytes);
}
}
private void copyHeapDumpObjectArrayDump(final Pipe pipe, @SuppressWarnings("unused") final int id) throws IOException {
pipe.pipeU4();
final long numElements = pipe.pipeU4();
pipe.pipeId();
for (long i = 0; i < numElements; i++) {
pipe.pipeId();
}
}
/*
* PRIMITIVE ARRAY DUMP * 0x23
* ID array object ID
* u4 stack trace serial number
* u4 number of elements
* u1 element type (See Basic Type)
* [u1]* elements (packed array)
*/
private void copyHeapDumpPrimitiveArrayDump(final Pipe pipe, @SuppressWarnings("unused") final int id) throws IOException {
pipe.pipeU4();
final long numElements = pipe.pipeU4();
final int elementType = pipe.pipeU1();
final int elementSize = BasicType.findValueSize(elementType, pipe.getIdSize());
final long numBytes = Math.multiplyExact(numElements, elementSize);
if (shouldApplyArraySanitization(elementType)) {
applySanitization(pipe, numBytes);
} else {
pipe.pipe(numBytes);
}
}
private boolean shouldApplyArraySanitization(final int elementType) {
if (!enableSanitization) {
return false;
}
final Optional<BasicType> typeOptional = BasicType.findByU1Code(elementType);
if (sanitizeByteCharArraysOnly) {
return typeOptional.filter(type -> type == BasicType.BYTE || type == BasicType.CHAR)
.isPresent();
}
return typeOptional.filter(type -> type != BasicType.OBJECT)
.isPresent();
}
private void applySanitization(final Pipe pipe, final long numBytes) throws IOException {
pipe.skipInput(numBytes);
final byte[] replacementData = sanitizationText.getBytes(StandardCharsets.UTF_8);
try (final InputStream replacementDataStream = new InfiniteCircularInputStream(replacementData)) {
pipe.copyFrom(replacementDataStream, numBytes);
}
}
private boolean isHeapDumpRecord(final int tag) {
return tag == TAG_HEAP_DUMP || tag == TAG_HEAP_DUMP_SEGMENT;
}
}
| 6,386 |
0 | Create_ds/heap-dump-tool/src/main/java/com/paypal/heapdumptool | Create_ds/heap-dump-tool/src/main/java/com/paypal/heapdumptool/sanitizer/DataUnit.java | /*
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.paypal.heapdumptool.sanitizer;
/**
* A standard set of {@link DataSize} units.
*
* <p>The unit prefixes used in this class are
* <a href="https://en.wikipedia.org/wiki/Binary_prefix">binary prefixes</a>
* indicating multiplication by powers of 2. The following table displays the
* enum constants defined in this class and corresponding values.
*
* @author Stephane Nicoll
* @author Sam Brannen
* @since 5.1
* @see DataSize
*/
public enum DataUnit {
/**
* Bytes, represented by suffix {@code B}.
*/
BYTES("B", DataSize.ofBytes(1)),
/**
* Kilobytes, represented by suffix {@code KB}.
*/
KILOBYTES("KB", DataSize.ofKilobytes(1)),
/**
* Megabytes, represented by suffix {@code MB}.
*/
MEGABYTES("MB", DataSize.ofMegabytes(1)),
/**
* Gigabytes, represented by suffix {@code GB}.
*/
GIGABYTES("GB", DataSize.ofGigabytes(1)),
/**
* Terabytes, represented by suffix {@code TB}.
*/
TERABYTES("TB", DataSize.ofTerabytes(1));
private final String suffix;
private final DataSize size;
DataUnit(final String suffix, final DataSize size) {
this.suffix = suffix;
this.size = size;
}
DataSize size() {
return this.size;
}
/**
* Return the {@link DataUnit} matching the specified {@code suffix}.
* @param suffix one of the standard suffixes
* @return the {@link DataUnit} matching the specified {@code suffix}
* @throws IllegalArgumentException if the suffix does not match the suffix
* of any of this enum's constants
*/
public static DataUnit fromSuffix(final String suffix) {
for (final DataUnit candidate : values()) {
if (candidate.suffix.equals(suffix)) {
return candidate;
}
}
throw new IllegalArgumentException("Unknown data unit suffix '" + suffix + "'");
}
}
| 6,387 |
0 | Create_ds/heap-dump-tool/src/main/java/com/paypal/heapdumptool | Create_ds/heap-dump-tool/src/main/java/com/paypal/heapdumptool/sanitizer/DataSize.java | /*
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.paypal.heapdumptool.sanitizer;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* A data size, such as '12MB'.
*
* <p>This class models data size in terms of bytes and is immutable and thread-safe.
*
* <p>The terms and units used in this class are based on
* <a href="https://en.wikipedia.org/wiki/Binary_prefix">binary prefixes</a>
* indicating multiplication by powers of 2. Consult the following table and
* the Javadoc for {@link DataUnit} for details.
* </p>
* @author Stephane Nicoll
* @author Sam Brannen
* @since 5.1
* @see DataUnit
*/
public final class DataSize implements Comparable<DataSize> {
/**
* The pattern for parsing.
*/
private static final Pattern PATTERN = Pattern.compile("^([+\\-]?\\d+)([a-zA-Z]{0,2})$");
/**
* Bytes per Kilobyte.
*/
private static final long BYTES_PER_KB = 1024;
/**
* Bytes per Megabyte.
*/
private static final long BYTES_PER_MB = BYTES_PER_KB * 1024;
/**
* Bytes per Gigabyte.
*/
private static final long BYTES_PER_GB = BYTES_PER_MB * 1024;
/**
* Bytes per Terabyte.
*/
private static final long BYTES_PER_TB = BYTES_PER_GB * 1024;
private final long bytes;
private DataSize(final long bytes) {
this.bytes = bytes;
}
/**
* Obtain a {@link DataSize} representing the specified number of bytes.
* @param bytes the number of bytes, positive or negative
* @return a {@link DataSize}
*/
public static DataSize ofBytes(final long bytes) {
return new DataSize(bytes);
}
/**
* Obtain a {@link DataSize} representing the specified number of kilobytes.
* @param kilobytes the number of kilobytes, positive or negative
* @return a {@link DataSize}
*/
public static DataSize ofKilobytes(final long kilobytes) {
return new DataSize(Math.multiplyExact(kilobytes, BYTES_PER_KB));
}
/**
* Obtain a {@link DataSize} representing the specified number of megabytes.
* @param megabytes the number of megabytes, positive or negative
* @return a {@link DataSize}
*/
public static DataSize ofMegabytes(final long megabytes) {
return new DataSize(Math.multiplyExact(megabytes, BYTES_PER_MB));
}
/**
* Obtain a {@link DataSize} representing the specified number of gigabytes.
* @param gigabytes the number of gigabytes, positive or negative
* @return a {@link DataSize}
*/
public static DataSize ofGigabytes(final long gigabytes) {
return new DataSize(Math.multiplyExact(gigabytes, BYTES_PER_GB));
}
/**
* Obtain a {@link DataSize} representing the specified number of terabytes.
* @param terabytes the number of terabytes, positive or negative
* @return a {@link DataSize}
*/
public static DataSize ofTerabytes(final long terabytes) {
return new DataSize(Math.multiplyExact(terabytes, BYTES_PER_TB));
}
/**
* Obtain a {@link DataSize} representing an amount in the specified {@link DataUnit}.
* @param amount the amount of the size, measured in terms of the unit,
* positive or negative
* @return a corresponding {@link DataSize}
*/
public static DataSize of(final long amount, final DataUnit unit) {
Validate.notNull(unit, "Unit must not be null");
return new DataSize(Math.multiplyExact(amount, unit.size().toBytes()));
}
/**
* Obtain a {@link DataSize} from a text string such as {@code 12MB} using
* {@link DataUnit#BYTES} if no unit is specified.
* <p>
* Examples:
* <pre>
* "12KB" -- parses as "12 kilobytes"
* "5MB" -- parses as "5 megabytes"
* "20" -- parses as "20 bytes"
* </pre>
* @param text the text to parse
* @return the parsed {@link DataSize}
* @see #parse(CharSequence, DataUnit)
*/
public static DataSize parse(final CharSequence text) {
return parse(text, null);
}
/**
* Obtain a {@link DataSize} from a text string such as {@code 12MB} using
* the specified default {@link DataUnit} if no unit is specified.
* <p>
* The string starts with a number followed optionally by a unit matching one of the
* supported {@linkplain DataUnit suffixes}.
* <p>
* Examples:
* <pre>
* "12KB" -- parses as "12 kilobytes"
* "5MB" -- parses as "5 megabytes"
* "20" -- parses as "20 kilobytes" (where the {@code defaultUnit} is {@link DataUnit#KILOBYTES})
* </pre>
* @param text the text to parse
* @return the parsed {@link DataSize}
*/
public static DataSize parse(final CharSequence text, final DataUnit defaultUnit) {
Validate.notNull(text, "Text must not be null");
try {
final Matcher matcher = PATTERN.matcher(text);
Validate.isTrue(matcher.matches(), "Does not match data size pattern");
final DataUnit unit = determineDataUnit(matcher.group(2), defaultUnit);
final long amount = Long.parseLong(matcher.group(1));
return DataSize.of(amount, unit);
} catch (final Exception ex) {
throw new IllegalArgumentException("'" + text + "' is not a valid data size", ex);
}
}
private static DataUnit determineDataUnit(final String suffix, final DataUnit defaultUnit) {
final DataUnit defaultUnitToUse = (defaultUnit != null ? defaultUnit : DataUnit.BYTES);
return (StringUtils.isNotEmpty(suffix) ? DataUnit.fromSuffix(suffix) : defaultUnitToUse);
}
/**
* Checks if this size is negative, excluding zero.
* @return true if this size has a size less than zero bytes
*/
public boolean isNegative() {
return this.bytes < 0;
}
/**
* Return the number of bytes in this instance.
* @return the number of bytes
*/
public long toBytes() {
return this.bytes;
}
/**
* Return the number of kilobytes in this instance.
* @return the number of kilobytes
*/
public long toKilobytes() {
return this.bytes / BYTES_PER_KB;
}
/**
* Return the number of megabytes in this instance.
* @return the number of megabytes
*/
public long toMegabytes() {
return this.bytes / BYTES_PER_MB;
}
/**
* Return the number of gigabytes in this instance.
* @return the number of gigabytes
*/
public long toGigabytes() {
return this.bytes / BYTES_PER_GB;
}
/**
* Return the number of terabytes in this instance.
* @return the number of terabytes
*/
public long toTerabytes() {
return this.bytes / BYTES_PER_TB;
}
@Override
public int compareTo(final DataSize other) {
return Long.compare(this.bytes, other.bytes);
}
@Override
public String toString() {
return String.format("%dB", this.bytes);
}
@Override
public boolean equals(final Object other) {
if (this == other) {
return true;
}
if (other == null || getClass() != other.getClass()) {
return false;
}
final DataSize otherSize = (DataSize) other;
return (this.bytes == otherSize.bytes);
}
@Override
public int hashCode() {
return Long.hashCode(this.bytes);
}
}
| 6,388 |
0 | Create_ds/heap-dump-tool/src/main/java/com/paypal/heapdumptool | Create_ds/heap-dump-tool/src/main/java/com/paypal/heapdumptool/sanitizer/SanitizeCommand.java | package com.paypal.heapdumptool.sanitizer;
import com.paypal.heapdumptool.cli.CliCommand;
import org.apache.commons.text.StringEscapeUtils;
import picocli.CommandLine.Command;
import picocli.CommandLine.Option;
import picocli.CommandLine.Parameters;
import java.nio.file.Path;
import static com.paypal.heapdumptool.sanitizer.DataSize.ofMegabytes;
import static org.apache.commons.lang3.builder.ToStringBuilder.reflectionToString;
import static org.apache.commons.lang3.builder.ToStringStyle.MULTI_LINE_STYLE;
import static picocli.CommandLine.Help.Visibility.ALWAYS;
@Command(name = "sanitize", description = "Sanitize a heap dump by replacing byte and char array contents", abbreviateSynopsis = true)
public class SanitizeCommand implements CliCommand {
static final String DOCKER_REGISTRY_OPTION = "--docker-registry";
// to allow field injection from picocli, these variables can't be final
@Option(names = { "-d", DOCKER_REGISTRY_OPTION }, description = "docker registry hostname for bootstrapping heap-dump-tool docker image")
private String dockerRegistry;
@Parameters(index = "0", description = "Input heap dump .hprof. File or stdin")
private Path inputFile;
@Option(names = {"-a", "--tar-input"}, description = "Treat input as tar archive")
private boolean tarInput;
@Parameters(index = "1", description = "Output heap dump .hprof. File, stdout, or stderr")
private Path outputFile;
@Option(names = {"-z", "--zip-output"}, description = "Write zipped output", showDefaultValue = ALWAYS)
private boolean zipOutput;
@Option(names = {"-t", "--text"}, description = "Sanitization text to replace with", defaultValue = "\\0", showDefaultValue = ALWAYS)
private String sanitizationText = "\\0";
@Option(names = {"-s", "--sanitize-byte-char-arrays-only"}, description = "Sanitize byte/char arrays only", defaultValue = "true", showDefaultValue = ALWAYS)
private boolean sanitizeByteCharArraysOnly = true;
@Option(names = {"--sanitize-arrays-only"}, description = "Sanitize arrays only", defaultValue = "false", showDefaultValue = ALWAYS)
private boolean sanitizeArraysOnly;
@Option(names = {"-b", "--buffer-size"}, description = "Buffer size for reading and writing", defaultValue = "100MB", showDefaultValue = ALWAYS)
private DataSize bufferSize = ofMegabytes(100);
@Override
public Class<SanitizeCommandProcessor> getProcessorClass() {
return SanitizeCommandProcessor.class;
}
public DataSize getBufferSize() {
return bufferSize;
}
public void setBufferSize(final DataSize bufferSize) {
this.bufferSize = bufferSize;
}
public boolean isSanitizeByteCharArraysOnly() {
return sanitizeByteCharArraysOnly;
}
public void setSanitizeByteCharArraysOnly(final boolean sanitizeByteCharArraysOnly) {
this.sanitizeByteCharArraysOnly = sanitizeByteCharArraysOnly;
}
public boolean isSanitizeArraysOnly() {
return sanitizeArraysOnly;
}
public void setSanitizeArraysOnly(final boolean sanitizeArraysOnly) {
this.sanitizeArraysOnly = sanitizeArraysOnly;
}
public Path getInputFile() {
return inputFile;
}
public void setInputFile(final Path inputFile) {
this.inputFile = inputFile;
}
public boolean isTarInput() {
return tarInput;
}
public void setTarInput(final boolean tarInput) {
this.tarInput = tarInput;
}
public Path getOutputFile() {
return outputFile;
}
public void setOutputFile(final Path outputFile) {
this.outputFile = outputFile;
}
public String getSanitizationText() {
return StringEscapeUtils.unescapeJava(sanitizationText);
}
public void setSanitizationText(final String sanitizationText) {
// e.g. unescape user-supplied \\0 string (2 chars) to \0 string (1 char)
this.sanitizationText = StringEscapeUtils.unescapeJava(sanitizationText);
}
public boolean isZipOutput() {
return zipOutput;
}
public void setZipOutput(final boolean zipOutput) {
this.zipOutput = zipOutput;
}
@Override
public String toString() {
return reflectionToString(this, MULTI_LINE_STYLE);
}
}
| 6,389 |
0 | Create_ds/heap-dump-tool/src/main/java/com/paypal/heapdumptool | Create_ds/heap-dump-tool/src/main/java/com/paypal/heapdumptool/sanitizer/Pipe.java | package com.paypal.heapdumptool.sanitizer;
import com.paypal.heapdumptool.utils.ProgressMonitor;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.input.BoundedInputStream;
import org.apache.commons.lang3.Validate;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* For piping or copying data from input to output streams.
* Along the way, different data can be written by calling {@link #copyFrom(InputStream, long)} or {@link #writeU1(int)} methods.
*/
public class Pipe {
private final DataInputStream input;
private final DataOutputStream output;
private Integer idSize;
public Pipe(final InputStream input, final OutputStream output, final ProgressMonitor numBytesWrittenMonitor) {
this.input = new DataInputStream(input);
this.output = new DataOutputStream(numBytesWrittenMonitor.monitoredOutputStream(output));
}
private Pipe(final DataInputStream input, final DataOutputStream output, final Integer idSize) {
this.input = input;
this.output = output;
this.idSize = idSize;
}
/**
* Creates a copy of this pipe where only up to give count of bytes can read from input stream
*/
public Pipe newInputBoundedPipe(final long inputCount) {
final DataInputStream boundedInput = new DataInputStream(new BoundedInputStream(input, inputCount));
return new Pipe(boundedInput, output, idSize);
}
public int getIdSize() {
return idSize;
}
public void setIdSize(final int idSize) {
Validate.isTrue(idSize == 4 || idSize == 8, "Unknown id size: %s", idSize);
this.idSize = idSize;
}
public int readU1() throws IOException {
return input.read();
}
public void writeU1(final int u1) throws IOException {
output.write(u1);
}
public void copyFrom(final InputStream inputStream, final long count) throws IOException {
IOUtils.copyLarge(inputStream, output, 0, count);
}
public int pipeU1() throws IOException {
final int u1 = input.read();
output.write(u1);
return u1;
}
public int pipeU1IfPossible() throws IOException {
final int u1 = input.read();
if (u1 != -1) {
output.write(u1);
}
return u1;
}
public int pipeU2() throws IOException {
final int u2 = input.readShort();
output.writeShort(u2);
return u2;
}
public long pipeU4() throws IOException {
final int u4 = input.readInt();
output.writeInt(u4);
return Integer.toUnsignedLong(u4);
}
public long pipeId() throws IOException {
if (idSize == 4) {
return pipeU4();
} else {
final long value = input.readLong();
output.writeLong(value);
Validate.isTrue(value >= 0, "Small unsigned long expected");
return value;
}
}
public void pipe(final long count) throws IOException {
IOUtils.copyLarge(input, output, 0, count);
}
public void skipInput(final long count) throws IOException {
IOUtils.skipFully(input, count);
}
public String pipeNullTerminatedString() throws IOException {
int byteValue = Integer.MAX_VALUE;
final StringBuilder sb = new StringBuilder();
while (byteValue > 0) {
byteValue = input.read();
if (byteValue >= 0) {
output.write(byteValue);
sb.append((char) byteValue);
}
}
return sb.toString();
}
}
| 6,390 |
0 | Create_ds/heap-dump-tool/src/main/java/com/paypal/heapdumptool | Create_ds/heap-dump-tool/src/main/java/com/paypal/heapdumptool/sanitizer/BasicType.java | package com.paypal.heapdumptool.sanitizer;
import java.util.Optional;
import java.util.stream.Stream;
public enum BasicType {
OBJECT(2),
BOOLEAN(4),
CHAR(5),
FLOAT(6),
DOUBLE(7),
BYTE(8),
SHORT(9),
INT(10),
LONG(11);
private final int u1Code;
public static int findValueSize(final int u1Code, final int idSize) {
final BasicType basicType = findByU1Code(u1Code).orElseThrow(() -> new IllegalArgumentException("Unknown basic type code: " + u1Code));
return basicType.getValueSize(idSize);
}
public static Optional<BasicType> findByU1Code(final int u1Code) {
return Stream.of(BasicType.values())
.filter(basicType -> basicType.u1Code == u1Code)
.findFirst();
}
private BasicType(final int u1Code) {
this.u1Code = u1Code;
}
public int getU1Code() {
return u1Code;
}
private int getValueSize(final int idSize) {
switch (this) {
case OBJECT:
return idSize;
case BOOLEAN:
return 1;
case CHAR:
return 2;
case FLOAT:
return 4;
case DOUBLE:
return 8;
case BYTE:
return 1;
case SHORT:
return 2;
case INT:
return 4;
case LONG:
return 8;
default:
throw new IllegalArgumentException("Unknown basic type: " + this);
}
}
}
| 6,391 |
0 | Create_ds/heap-dump-tool/src/main/java/com/paypal/heapdumptool | Create_ds/heap-dump-tool/src/main/java/com/paypal/heapdumptool/sanitizer/SanitizeStreamFactory.java | package com.paypal.heapdumptool.sanitizer;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import static java.lang.Math.toIntExact;
/**
* Creates i/o streams for input/output files
*/
public class SanitizeStreamFactory {
private final SanitizeCommand command;
public SanitizeStreamFactory(final SanitizeCommand command) {
this.command = validate(command);
}
public InputStream newInputStream() throws IOException {
final Path inputFile = command.getInputFile();
final InputStream inputStream = getBufferSize() == 0
? newInputStream(inputFile)
: new BufferedInputStream(newInputStream(inputFile), getBufferSize());
if (command.isTarInput()) {
final TarArchiveInputStream tarStream = new TarArchiveInputStream(inputStream);
Validate.notNull(tarStream.getNextTarEntry(), "no tar entries");
return tarStream;
}
return inputStream;
}
public OutputStream newOutputStream() throws IOException {
final Path outputFile = command.getOutputFile();
final OutputStream output = getBufferSize() == 0
? Files.newOutputStream(outputFile)
: new BufferedOutputStream(Files.newOutputStream(outputFile), getBufferSize());
if (command.isZipOutput()) {
final ZipOutputStream zipStream = new ZipOutputStream(output);
final String name = getOutputFileName();
final String entryName = StringUtils.removeEnd(name, ".zip");
zipStream.putNextEntry(new ZipEntry(entryName));
return zipStream;
}
return output;
}
protected InputStream newInputStream(final Path inputFile) throws IOException {
final String name = inputFile.getFileName().toString();
return StringUtils.equalsAny(name, "-", "stdin", "0")
? System.in
: Files.newInputStream(inputFile);
}
private static SanitizeCommand validate(final SanitizeCommand command) {
final Path outputFile = command.getOutputFile();
Validate.isTrue(!command.getInputFile().equals(outputFile), "input and output files cannot be the same");
return command;
}
private String getOutputFileName() {
final Path outputFile = command.getOutputFile();
return outputFile.getFileName().toString();
}
private int getBufferSize() {
final DataSize bufferSize = command.getBufferSize();
return toIntExact(bufferSize.toBytes());
}
}
| 6,392 |
0 | Create_ds/heap-dump-tool/src/main/java/com/paypal/heapdumptool | Create_ds/heap-dump-tool/src/main/java/com/paypal/heapdumptool/hserr/SanitizeHserrCommandProcessor.java | package com.paypal.heapdumptool.hserr;
import com.paypal.heapdumptool.cli.CliCommandProcessor;
import com.paypal.heapdumptool.sanitizer.SanitizeCommand;
import com.paypal.heapdumptool.sanitizer.SanitizeStreamFactory;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import static com.paypal.heapdumptool.utils.DateTimeTool.getFriendlyDuration;
public class SanitizeHserrCommandProcessor implements CliCommandProcessor {
private static final Logger LOGGER = LoggerFactory.getLogger(SanitizeHserrCommandProcessor.class);
private final SanitizeHserrCommand command;
private final SanitizeStreamFactory streamFactory;
public SanitizeHserrCommandProcessor(final SanitizeHserrCommand command) {
this(command, new SanitizeStreamFactory(asSanitizeCommand(command)));
}
public SanitizeHserrCommandProcessor(final SanitizeHserrCommand command, final SanitizeStreamFactory streamFactory) {
this.command = command;
this.streamFactory = streamFactory;
}
@Override
public void process() throws Exception {
LOGGER.info("Starting hs_err sanitization");
LOGGER.info("Input File: {}", command.getInputFile());
LOGGER.info("Output File: {}", command.getOutputFile());
final Instant now = Instant.now();
try (final InputStream inputStream = streamFactory.newInputStream();
final OutputStream outputStream = streamFactory.newOutputStream()) {
final List<String> lines = IOUtils.readLines(inputStream, StandardCharsets.UTF_8);
final List<String> sanitizedLines = sanitize(lines);
IOUtils.writeLines(sanitizedLines, System.lineSeparator(), outputStream, StandardCharsets.UTF_8);
}
LOGGER.info("Finished hs_err sanitization in {}", getFriendlyDuration(now));
}
private List<String> sanitize(final List<String> lines) {
boolean inEnvVarSection = false;
final List<String> sanitizedLines = new ArrayList<>();
for (final String line : lines) {
String newLine = line;
if (line.startsWith("Environment Variables:")) {
inEnvVarSection = true;
} else if (inEnvVarSection) {
if (line.isEmpty()) {
inEnvVarSection = false;
} else {
final String key = StringUtils.substringBefore(line, "=");
newLine = key + "=****";
}
}
sanitizedLines.add(newLine);
}
return sanitizedLines;
}
private static SanitizeCommand asSanitizeCommand(final SanitizeHserrCommand command) {
final SanitizeCommand sanitizeCommand = new SanitizeCommand();
sanitizeCommand.setInputFile(command.getInputFile());
sanitizeCommand.setOutputFile(command.getOutputFile());
return sanitizeCommand;
}
}
| 6,393 |
0 | Create_ds/heap-dump-tool/src/main/java/com/paypal/heapdumptool | Create_ds/heap-dump-tool/src/main/java/com/paypal/heapdumptool/hserr/SanitizeHserrCommand.java | package com.paypal.heapdumptool.hserr;
import com.paypal.heapdumptool.cli.CliCommand;
import picocli.CommandLine.Command;
import picocli.CommandLine.Parameters;
import java.nio.file.Path;
import static org.apache.commons.lang3.builder.ToStringBuilder.reflectionToString;
import static org.apache.commons.lang3.builder.ToStringStyle.MULTI_LINE_STYLE;
@Command(name = "sanitize-hserr", description = "Sanitize fatal error log by censoring environment variable values", abbreviateSynopsis = true)
public class SanitizeHserrCommand implements CliCommand {
// to allow field injection from picocli, these variables can't be final
@Parameters(index = "0", description = "Input hs_err_pid* fatal error log. File or stdin")
private Path inputFile;
@Parameters(index = "1", description = "Output hs_err_pid* fatal error log. File, stdout, or stderr")
private Path outputFile;
@Override
public Class<SanitizeHserrCommandProcessor> getProcessorClass() {
return SanitizeHserrCommandProcessor.class;
}
public Path getInputFile() {
return inputFile;
}
public void setInputFile(final Path inputFile) {
this.inputFile = inputFile;
}
public Path getOutputFile() {
return outputFile;
}
public void setOutputFile(final Path outputFile) {
this.outputFile = outputFile;
}
@Override
public String toString() {
return reflectionToString(this, MULTI_LINE_STYLE);
}
}
| 6,394 |
0 | Create_ds/heap-dump-tool/src/main/java/com/paypal/heapdumptool | Create_ds/heap-dump-tool/src/main/java/com/paypal/heapdumptool/utils/ProcessTool.java | package com.paypal.heapdumptool.utils;
import org.apache.commons.io.IOUtils;
import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Future;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.Collections.unmodifiableList;
import static java.util.concurrent.CompletableFuture.supplyAsync;
/**
* Convenience tool for running os processes
*/
public class ProcessTool {
// for mocking
public static ProcessBuilder processBuilder(final String... cmd) {
return new ProcessBuilder(cmd);
}
public static ProcessResult run(final String... cmd) throws Exception {
final Process process = processBuilder(cmd).start();
try {
process.getOutputStream().close();
final InputStream stderrStream = process.getErrorStream();
final InputStream stdoutStream = process.getInputStream();
final Future<String> stderrFuture = supplyAsync(() -> readStream(stderrStream));
final Future<String> stdoutFuture = supplyAsync(() -> readStream(stdoutStream));
final int exitCode = process.waitFor();
return new ProcessResult(exitCode, stdoutFuture.get(), stderrFuture.get());
} finally {
process.destroy();
}
}
static String readStream(final InputStream stream) {
try {
return IOUtils.toString(stream, UTF_8);
} catch (final IOException e) {
throw new UncheckedIOException(e);
}
}
private ProcessTool() {
throw new AssertionError();
}
public static class ProcessResult {
public final int exitCode;
public final String stdout;
public final String stderr;
public ProcessResult(final int exitCode, final String stdout, final String stderr) {
this.exitCode = exitCode;
this.stdout = stdout;
this.stderr = stderr;
}
public List<String> stdoutLines() {
return unmodifiableList(Arrays.asList(stdout.split("\n")));
}
}
}
| 6,395 |
0 | Create_ds/heap-dump-tool/src/main/java/com/paypal/heapdumptool | Create_ds/heap-dump-tool/src/main/java/com/paypal/heapdumptool/utils/ProgressMonitor.java | package com.paypal.heapdumptool.utils;
import com.paypal.heapdumptool.sanitizer.DataSize;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.input.CountingInputStream;
import org.apache.commons.io.output.CountingOutputStream;
import org.apache.commons.lang3.mutable.MutableLong;
import org.slf4j.Logger;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.function.Consumer;
@FunctionalInterface
public interface ProgressMonitor extends Consumer<Long> {
/**
* Create a new {@link ProgressMonitor} that logs a message for each stepSize processed
*/
public static ProgressMonitor numBytesProcessedMonitor(final DataSize stepSize, final Logger logger) {
final long stepSizeBytes = stepSize.toBytes();
final MutableLong steps = new MutableLong();
return numBytesProcessed -> {
final long currentSteps = numBytesProcessed / stepSizeBytes;
if (currentSteps != steps.getValue().longValue()) {
steps.setValue(currentSteps);
logger.info("Processed {}", FileUtils.byteCountToDisplaySize(numBytesProcessed));
}
};
}
/**
* Create a OutputStream monitored by this
*/
public default OutputStream monitoredOutputStream(final OutputStream output) {
final ProgressMonitor monitor = this;
return new CountingOutputStream(output) {
@Override
protected void beforeWrite(final int n) {
super.beforeWrite(n);
monitor.accept(getByteCount());
}
};
}
/**
* Create a OutputStream monitored by this
*/
public default InputStream monitoredInputStream(final InputStream input) {
final ProgressMonitor monitor = this;
return new CountingInputStream(input) {
@Override
protected void afterRead(final int n) {
super.afterRead(n);
monitor.accept(getByteCount());
}
};
}
}
| 6,396 |
0 | Create_ds/heap-dump-tool/src/main/java/com/paypal/heapdumptool | Create_ds/heap-dump-tool/src/main/java/com/paypal/heapdumptool/utils/DateTimeTool.java | package com.paypal.heapdumptool.utils;
import java.time.Duration;
import java.time.Instant;
import static java.time.temporal.ChronoUnit.SECONDS;
import static java.util.Locale.ENGLISH;
public class DateTimeTool {
public static String getFriendlyDuration(final Instant start) {
final Instant startSeconds = start.truncatedTo(SECONDS);
final Instant endSeconds = Instant.now().truncatedTo(SECONDS);
final Duration duration = Duration.between(startSeconds, endSeconds);
return duration.toString()
.substring(2)
.toLowerCase(ENGLISH);
}
private DateTimeTool() {
throw new AssertionError();
}
}
| 6,397 |
0 | Create_ds/heap-dump-tool/src/main/java/com/paypal/heapdumptool | Create_ds/heap-dump-tool/src/main/java/com/paypal/heapdumptool/utils/CallableTool.java | package com.paypal.heapdumptool.utils;
import java.util.concurrent.Callable;
public class CallableTool {
public static <T> T callQuietlyWithDefault(final T defaultValue, final Callable<T> callable) {
try {
return callable.call();
} catch (final Exception ignore) {
return defaultValue;
}
}
private CallableTool() {
throw new AssertionError();
}
}
| 6,398 |
0 | Create_ds/heap-dump-tool/src/main/java/com/paypal/heapdumptool | Create_ds/heap-dump-tool/src/main/java/com/paypal/heapdumptool/cli/CliBootstrap.java | package com.paypal.heapdumptool.cli;
import com.paypal.heapdumptool.Application.VersionProvider;
import org.apache.commons.lang3.exception.ExceptionUtils;
import java.lang.reflect.InvocationTargetException;
import static org.apache.commons.lang3.reflect.ConstructorUtils.invokeConstructor;
public class CliBootstrap {
public static <T extends CliCommand> boolean runCommand(final T command) throws Exception {
VersionProvider.printVersion();
final Class<? extends CliCommandProcessor> clazz = command.getProcessorClass();
try {
final CliCommandProcessor processor = invokeConstructor(clazz, command);
processor.process();
} catch (final InvocationTargetException e) {
if (e.getCause() != null) {
ExceptionUtils.rethrow(e.getCause());
}
throw e;
}
return true;
}
private CliBootstrap() {
throw new AssertionError();
}
}
| 6,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.