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-axis1-java/axis-rt-core/src/main/java/org/apache/axis/client
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/client/async/Status.java
/* * Copyright 2001-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.axis.client.async; import org.apache.axis.constants.Enum; /** * Status of the async request * * @author Davanum Srinivas (dims@yahoo.com) */ public class Status extends Enum { /** * Field type */ private static final Type type = new Type(); /** * Field NONE_STR */ public static final String NONE_STR = "none"; /** * Field INTERRUPTED_STR */ public static final String INTERRUPTED_STR = "interrupted"; /** * Field COMPLETED_STR */ public static final String COMPLETED_STR = "completed"; /** * Field EXCEPTION_STR */ public static final String EXCEPTION_STR = "exception"; /** * Field NONE */ public static final Status NONE = type.getStatus(NONE_STR); /** * Field INTERRUPTED */ public static final Status INTERRUPTED = type.getStatus(INTERRUPTED_STR); /** * Field COMPLETED */ public static final Status COMPLETED = type.getStatus(COMPLETED_STR); /** * Field EXCEPTION */ public static final Status EXCEPTION = type.getStatus(EXCEPTION_STR); /** * Field DEFAULT */ public static final Status DEFAULT = NONE; static { type.setDefault(DEFAULT); } /** * Method getDefault * * @return */ public static Status getDefault() { return (Status) type.getDefault(); } /** * Method getStatus * * @param style * @return */ public static final Status getStatus(int style) { return type.getStatus(style); } /** * Method getStatus * * @param style * @return */ public static final Status getStatus(String style) { return type.getStatus(style); } /** * Method getStatus * * @param style * @param dephault * @return */ public static final Status getStatus(String style, Status dephault) { return type.getStatus(style, dephault); } /** * Method isValid * * @param style * @return */ public static final boolean isValid(String style) { return type.isValid(style); } /** * Method size * * @return */ public static final int size() { return type.size(); } /** * Method getUses * * @return */ public static final String[] getUses() { return type.getEnumNames(); } /** * Class Type * * @author * @version %I%, %G% */ public static class Type extends Enum.Type { /** * Constructor Type */ private Type() { super("status", new Enum[]{new Status(0, NONE_STR), new Status(1, INTERRUPTED_STR), new Status(2, COMPLETED_STR), new Status(3, EXCEPTION_STR), }); } /** * Method getStatus * * @param status * @return */ public final Status getStatus(int status) { return (Status) this.getEnum(status); } /** * Method getStatus * * @param status * @return */ public final Status getStatus(String status) { return (Status) this.getEnum(status); } /** * Method getStatus * * @param status * @param dephault * @return */ public final Status getStatus(String status, Status dephault) { return (Status) this.getEnum(status, dephault); } } /** * Constructor Status * * @param value * @param name */ private Status(int value, String name) { super(type, value, name); } }
7,800
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/client
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/client/async/IAsyncCallback.java
/* * Copyright 2001-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.axis.client.async; /** * Callback for Async notification * * @author Davanum Srinivas (dims@yahoo.com) */ public interface IAsyncCallback { /** * Method onCompletion * * @param event */ public void onCompletion(IAsyncResult event); }
7,801
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/client
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/client/async/AsyncResult.java
/* * Copyright 2001-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.axis.client.async; import javax.xml.namespace.QName; /** * Access the results of the Async call * * @author Davanum Srinivas (dims@yahoo.com) */ public class AsyncResult implements IAsyncResult, Runnable { /** * Field thread */ private Thread thread = null; /** * Field response */ private Object response = null; /** * Field exception */ private Throwable exception = null; /** * Field ac */ private AsyncCall ac = null; /** * Field opName */ private QName opName = null; /** * Field params */ private Object[] params = null; /** * Field status */ private Status status = Status.NONE; /** * Constructor AsyncResult * * @param ac * @param opName * @param params */ public AsyncResult(AsyncCall ac, QName opName, Object[] params) { this.ac = ac; this.opName = opName; this.params = params; if (opName == null) { this.opName = ac.getCall().getOperationName(); } thread = new Thread(this); thread.setDaemon(true); thread.start(); } /** * Method abort */ public void abort() { thread.interrupt(); status = Status.INTERRUPTED; } /** * Method getStatus * * @return */ public Status getStatus() { return status; } /** * Method waitFor * * @param timeout * @throws InterruptedException */ public void waitFor(long timeout) throws InterruptedException { thread.wait(timeout); } /** * Method getResponse * * @return */ public Object getResponse() { return response; } /** * Method getException * * @return */ public Throwable getException() { return exception; } /** * Method run */ public void run() { try { response = ac.getCall().invoke(opName, params); status = Status.COMPLETED; } catch (Throwable e) { exception = e; status = Status.EXCEPTION; } finally { IAsyncCallback callback = ac.getCallback(); if (callback != null) { callback.onCompletion(this); } } } }
7,802
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/client
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/client/async/AsyncCall.java
/* * Copyright 2001-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.axis.client.async; import org.apache.axis.client.Call; import javax.xml.namespace.QName; /** * Support for Asynchronous call * * @author Davanum Srinivas (dims@yahoo.com) */ public class AsyncCall { /** * Field call */ private Call call = null; /** * Field callback */ private IAsyncCallback callback = null; /** * Constructor AsyncCall * * @param call */ public AsyncCall(Call call) { this(call, null); } /** * Constructor AsyncCall * * @param call * @param callback */ public AsyncCall(Call call, IAsyncCallback callback) { this.call = call; this.callback = callback; } /** * Method getCallback * * @return */ public IAsyncCallback getCallback() { return callback; } /** * Method setCallback * * @param callback */ public void setCallback(IAsyncCallback callback) { this.callback = callback; } /** * Method invoke * * @param inputParams * @return */ public IAsyncResult invoke(Object[] inputParams) { return new AsyncResult(this, null, inputParams); } /** * Method invoke * * @param qName * @param inputParams * @return */ public IAsyncResult invoke(QName qName, Object[] inputParams) { return new AsyncResult(this, qName, inputParams); } /** * Method getCall * * @return */ public Call getCall() { return call; } }
7,803
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/handlers/JAXRPCHandler.java
/* * Copyright 2001-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.axis.handlers; import org.apache.axis.AxisFault; import org.apache.axis.MessageContext; import org.apache.axis.components.logger.LogFactory; import org.apache.commons.logging.Log; import java.util.Map; /** * Handles JAXRPC style handlers. * * @author Davanum Srinivas (dims@yahoo.com) */ public class JAXRPCHandler extends BasicHandler { protected static Log log = LogFactory.getLog(JAXRPCHandler.class.getName()); protected HandlerChainImpl impl = new HandlerChainImpl(); public void init() { super.init(); String className = (String)getOption("className"); if (className != null) { addNewHandler(className, getOptions()); } } public void addNewHandler(String className, Map options) { impl.addNewHandler(className, options); } public void invoke(MessageContext msgContext) throws AxisFault { log.debug("Enter: JAXRPCHandler::enter invoke"); if (!msgContext.getPastPivot()) { impl.handleRequest(msgContext); } else { impl.handleResponse(msgContext); } log.debug("Enter: JAXRPCHandler::exit invoke"); } public void onFault(MessageContext msgContext) { impl.handleFault(msgContext); } public void cleanup() { impl.destroy(); } }
7,804
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/handlers/DebugHandler.java
/* * Copyright 2001-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.axis.handlers ; import org.apache.axis.AxisFault; import org.apache.axis.Constants; import org.apache.axis.Message; import org.apache.axis.MessageContext; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.message.SOAPEnvelope; import org.apache.axis.message.SOAPHeaderElement; import org.apache.axis.utils.Messages; import org.apache.commons.logging.Log; /** * * @author Doug Davis (dug@us.ibm.com) */ public class DebugHandler extends BasicHandler { protected static Log log = LogFactory.getLog(DebugHandler.class.getName()); public static final String NS_URI_DEBUG = "http://xml.apache.org/axis/debug"; public void invoke(MessageContext msgContext) throws AxisFault { log.debug("Enter: DebugHandler::invoke"); try { Message msg = msgContext.getRequestMessage(); SOAPEnvelope message = (SOAPEnvelope)msg.getSOAPEnvelope(); SOAPHeaderElement header = message. getHeaderByName(NS_URI_DEBUG, "Debug"); if (header != null) { Integer i = ((Integer)header .getValueAsType(Constants.XSD_INT)); if (i == null) throw new AxisFault(Messages.getMessage("cantConvert03")); int debugVal = i.intValue(); log.debug(Messages.getMessage("debugLevel00", "" + debugVal) ); //Debug.setDebugLevel(debugVal); header.setProcessed(true); } } catch( Exception e ) { log.error( Messages.getMessage("exception00"), e ); throw AxisFault.makeFault(e); } log.debug("Exit: DebugHandler::invoke"); } public void onFault(MessageContext msgContext) { log.debug("Enter: DebugHandler::onFault"); log.debug("Exit: DebugHandler::onFault"); } };
7,805
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/handlers/SimpleAuthenticationHandler.java
/* * Copyright 2001-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.axis.handlers ; import org.apache.axis.AxisFault; import org.apache.axis.MessageContext; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.security.AuthenticatedUser; import org.apache.axis.security.SecurityProvider; import org.apache.axis.security.simple.SimpleSecurityProvider; import org.apache.axis.utils.Messages; import org.apache.commons.logging.Log; /** * Just a simple Authentication Handler to see if the user * specified in the Bag in the MessageContext is allowed to continue. * * Just look for 'user' and 'password' in a file called 'users.lst'. * * Replace this with your 'real' authenication code. * * @author Doug Davis (dug@us.ibm.com) * @author Sam Ruby (rubys@us.ibm.com) */ public class SimpleAuthenticationHandler extends BasicHandler { protected static Log log = LogFactory.getLog(SimpleAuthenticationHandler.class.getName()); /** * Authenticate the user and password from the msgContext */ public void invoke(MessageContext msgContext) throws AxisFault { if (log.isDebugEnabled()) { log.debug("Enter: SimpleAuthenticationHandler::invoke"); } SecurityProvider provider = (SecurityProvider)msgContext.getProperty(MessageContext.SECURITY_PROVIDER); if (provider == null) { provider = new SimpleSecurityProvider(); msgContext.setProperty(MessageContext.SECURITY_PROVIDER, provider); } if (provider != null) { String userID = msgContext.getUsername(); if (log.isDebugEnabled()) { log.debug( Messages.getMessage("user00", userID) ); } // in order to authenticate, the user must exist if ( userID == null || userID.equals("")) throw new AxisFault( "Server.Unauthenticated", Messages.getMessage("cantAuth00", userID), null, null ); String passwd = msgContext.getPassword(); if (log.isDebugEnabled()) { log.debug( Messages.getMessage("password00", passwd) ); } AuthenticatedUser authUser = provider.authenticate(msgContext); // if a password is defined, then it must match if ( authUser == null) throw new AxisFault( "Server.Unauthenticated", Messages.getMessage("cantAuth01", userID), null, null ); if (log.isDebugEnabled()) { log.debug( Messages.getMessage("auth00", userID) ); } msgContext.setProperty(MessageContext.AUTHUSER, authUser); } if (log.isDebugEnabled()) { log.debug("Exit: SimpleAuthenticationHandler::invoke"); } } };
7,806
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/handlers/BasicHandler.java
/* * Copyright 2001-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.axis.handlers; import org.apache.axis.AxisFault; import org.apache.axis.Handler; import org.apache.axis.MessageContext; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.utils.LockableHashtable; import org.apache.commons.logging.Log; import org.w3c.dom.Document; import org.w3c.dom.Element; import javax.xml.namespace.QName; import java.util.Enumeration; import java.util.Hashtable; import java.util.List; /** <code>BasicHandler</code> is a utility class which implements simple * property setting/getting behavior, and stubs out a lot of the Handler * methods. Extend this class to make writing your Handlers easier, and * then override what you need to. * * @author Glen Daniels (gdaniels@allaire.com) * @author Doug Davis (dug@us.ibm.com */ public abstract class BasicHandler implements Handler { private static Log log = LogFactory.getLog(BasicHandler.class.getName()); protected boolean makeLockable = false; protected Hashtable options; protected String name; /** * Should this Handler use a LockableHashtable for options? * Default is 'false'. */ protected void setOptionsLockable(boolean makeLockable) { this.makeLockable = makeLockable; } protected void initHashtable() { if (makeLockable) { options = new LockableHashtable(); } else { options = new Hashtable(); } } /** * Stubbed-out methods. Override in your child class to implement * any real behavior. Note that there is NOT a stub for invoke(), since * we require any Handler derivative to implement that. */ public void init() { } public void cleanup() { } public boolean canHandleBlock(QName qname) { return false; } public void onFault(MessageContext msgContext) { } /** * Set the given option (name/value) in this handler's bag of options */ public void setOption(String name, Object value) { if ( options == null ) initHashtable(); options.put( name, value ); } /** * Set a default value for the given option: * if the option is not already set, then set it. * if the option is already set, then do not set it. * <p> * If this is called multiple times, the first with a non-null value * if 'value' will set the default, remaining calls will be ignored. * <p> * Returns true if value set (by this call), otherwise false; */ public boolean setOptionDefault(String name, Object value) { boolean val = (options == null || options.get(name) == null) && value != null; if (val) { setOption(name, value); } return val; } /** * Returns the option corresponding to the 'name' given */ public Object getOption(String name) { if ( options == null ) return( null ); return( options.get(name) ); } /** * Return the entire list of options */ public Hashtable getOptions() { return( options ); } public void setOptions(Hashtable opts) { options = opts; } /** * Set the name (i.e. registry key) of this Handler */ public void setName(String name) { this.name = name; } /** * Return the name (i.e. registry key) for this Handler */ public String getName() { return name; } public Element getDeploymentData(Document doc) { log.debug("Enter: BasicHandler::getDeploymentData"); Element root = doc.createElementNS("", "handler"); root.setAttribute( "class", this.getClass().getName() ); options = this.getOptions(); if ( options != null ) { Enumeration e = options.keys(); while ( e.hasMoreElements() ) { String k = (String) e.nextElement(); Object v = options.get(k); Element e1 = doc.createElementNS("", "option" ); e1.setAttribute( "name", k ); e1.setAttribute( "value", v.toString() ); root.appendChild( e1 ); } } log.debug("Exit: BasicHandler::getDeploymentData"); return( root ); } public void generateWSDL(MessageContext msgContext) throws AxisFault { } /** * Return a list of QNames which this Handler understands. By returning * a particular QName here, we are committing to fulfilling any contracts * defined in the specification of the SOAP header with that QName. */ public List getUnderstoodHeaders() { return null; } }
7,807
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/handlers/EchoHandler.java
/* * Copyright 2001-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.axis.handlers ; import org.apache.axis.AxisFault; import org.apache.axis.Message; import org.apache.axis.MessageContext; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.message.SOAPEnvelope; import org.apache.axis.utils.Messages; import org.apache.axis.utils.XMLUtils; import org.apache.commons.logging.Log; import org.w3c.dom.Document; import java.io.ByteArrayInputStream; /** * * @author Doug Davis (dug@us.ibm.com) */ public class EchoHandler extends BasicHandler { protected static Log log = LogFactory.getLog(EchoHandler.class.getName()); public void invoke(MessageContext msgContext) throws AxisFault { log.debug("Enter: EchoHandler::invoke"); try { Message msg = msgContext.getRequestMessage(); SOAPEnvelope env = (SOAPEnvelope) msg.getSOAPEnvelope(); msgContext.setResponseMessage( new Message( env ) ); } catch( Exception e ) { log.error( Messages.getMessage("exception00"), e ); throw AxisFault.makeFault(e); } log.debug("Exit: EchoHandler::invoke"); } public String wsdlStart1 = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>" + "<definitions xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" \n" + "xmlns:http=\"http://schemas.xmlsoap.org/wsdl/http/\" \n" + "xmlns:mime=\"http://schemas.xmlsoap.org/wsdl/mime/\" \n" + "xmlns:soap=\"http://schemas.xmlsoap.org/wsdl/soap/\" \n" + "xmlns:soapenc=\"http://schemas.xmlsoap.org/soap/encoding/\" \n" + "xmlns:s0=\"http://tempuri.org/EchoService\" \n"+ "targetNamespace=\"http://tempuri.org/EchoService\" \n" + "xmlns=\"http://schemas.xmlsoap.org/wsdl/\">" + "<message name=\"request\">" + "<part name=\"content\" type=\"xsd:anyType\" />" + "</message>" + "<message name=\"response\">" + "<part name=\"content\" element=\"xsd:anyType\" />" + "</message>" + "<portType name=\"EchoSoap\">" + "<operation name=\"doIt\">" + "<input message=\"s0:request\" /> " + "<output message=\"s0:response\" /> " + "</operation>" + "</portType>" + "<binding name=\"EchoSoap\" type=\"s0:EchoSoap\">" + "<soap:binding transport=\"http://schemas.xmlsoap.org/soap/http\" style=\"document\" />" + "<operation name=\"doIt\">" + "<soap:operation soapAction=\"http://tempuri.org/Echo\" style=\"document\" />" + "<input>" + "<soap:body use=\"literal\" />" + "</input>" + "<output>" + "<soap:body use=\"literal\" />" + "</output>" + "</operation>" + "</binding>" + "<service name=\"Echo\">" + "<port name=\"EchoSoap\" binding=\"s0:EchoSoap\">" + "<soap:address location=\"http://"; public String wsdlStart = "<?xml version=\"1.0\" encoding=\"UTF-8\"?> \n"+ "<wsdl:definitions targetNamespace=\"http://handlers.apache.org/EchoService\" \n"+ "xmlns=\"http://schemas.xmlsoap.org/wsdl/\" \n"+ "xmlns:apachesoap=\"http://xml.apache.org/xml-soap\" \n"+ "xmlns:impl=\"http://handlers.apache.org/EchoService\" \n"+ "xmlns:intf=\"http://handlers.apache.org/EchoService\" \n"+ "xmlns:soapenc=\"http://schemas.xmlsoap.org/soap/encoding/\" \n"+ "xmlns:wsdl=\"http://schemas.xmlsoap.org/wsdl/\" \n"+ "xmlns:wsdlsoap=\"http://schemas.xmlsoap.org/wsdl/soap/\" \n"+ "xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"> \n"+ "<wsdl:types> \n"+ "<schema targetNamespace=\"http://handlers.apache.org/EchoService\" \n" + "xmlns=\"http://www.w3.org/2001/XMLSchema\"> \n"+ "<xsd:import namespace=\"http://schemas.xmlsoap.org/soap/encoding/\"/> \n"+ "<xsd:complexType name=\"echoElements\"> \n" + " <xsd:sequence> \n" + " <xsd:element name=\"content\" type=\"xsd:anyType\"/> \n"+ " </xsd:sequence>\n"+ "</xsd:complexType> \n" + "<xsd:complexType name=\"echoElementsReturn\"> \n" + " <xsd:sequence> \n" + " <xsd:element name=\"content\" type=\"xsd:anyType\"/> \n"+ " </xsd:sequence> \n" + "</xsd:complexType> \n" + "</schema> \n"+ "</wsdl:types> \n"+ " <wsdl:message name=\"echoElementsResponse\"> \n"+ " <wsdl:part type=\"impl:echoElementsReturn\" name=\"echoElementsReturn\"/> \n"+ " </wsdl:message> \n"+ " <wsdl:message name=\"echoElementsRequest\"> \n"+ " <wsdl:part type=\"impl:echoElements\" name=\"part\"/> \n"+ " </wsdl:message> \n"+ " <wsdl:portType name=\"EchoService\"> \n"+ " <wsdl:operation name=\"doIt\"> \n"+ " <wsdl:input message=\"impl:echoElementsRequest\" name=\"echoElementsRequest\"/> \n"+ " <wsdl:output message=\"impl:echoElementsResponse\" name=\"echoElementsResponse\"/> \n"+ " </wsdl:operation> \n"+ " </wsdl:portType> \n"+ " <wsdl:binding name=\"EchoServiceSoapBinding\" type=\"impl:EchoService\"> \n"+ " <wsdlsoap:binding style=\"document\" transport=\"http://schemas.xmlsoap.org/soap/http\"/> \n"+ " <wsdl:operation name=\"doIt\"> \n"+ " <wsdlsoap:operation soapAction=\"\"/> \n"+ " <wsdl:input name=\"echoElementsRequest\"> \n"+ " <wsdlsoap:body namespace=\"http://handlers.apache.org/EchoService\" use=\"literal\"/> \n"+ " </wsdl:input> \n"+ " <wsdl:output name=\"echoElementsResponse\"> \n"+ " <wsdlsoap:body namespace=\"http://handlers.apache.org/EchoService\" use=\"literal\"/> \n"+ " </wsdl:output> \n"+ " </wsdl:operation> \n"+ " </wsdl:binding> \n"+ " <wsdl:service name=\"EchoService\"> \n"+ " <wsdl:port binding=\"impl:EchoServiceSoapBinding\" name=\"EchoService\"> \n"+ " <wsdlsoap:address location=\""; String wsdlEnd = " \"/></wsdl:port>\n" + "</wsdl:service>\n" + "</wsdl:definitions>\n"; public void generateWSDL(MessageContext msgContext) throws AxisFault { try { String url = msgContext.getStrProp(MessageContext.TRANS_URL); String wsdlString = wsdlStart + url + wsdlEnd; Document doc = XMLUtils.newDocument(new ByteArrayInputStream(wsdlString.getBytes("UTF-8"))); msgContext.setProperty("WSDL", doc); } catch (Exception e) { throw AxisFault.makeFault(e); } } };
7,808
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/handlers/LogHandler.java
/* * Copyright 2001-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.axis.handlers ; import org.apache.axis.AxisFault; import org.apache.axis.Message; import org.apache.axis.MessageContext; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.utils.Messages; import org.apache.commons.logging.Log; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; /** * A simple Handler which logs the request and response messages to either * the console or a specified file (default "axis.log"). * * To use this, deploy it either in both the request and response flows * (global, service, or transport) or in just the response flow. If deployed * in both places, you'll also get an elapsed time indication, which can be * handy for debugging. * * @author Doug Davis (dug@us.ibm.com) * @author Glen Daniels (gdaniels@apache.org) */ public class LogHandler extends BasicHandler { protected static Log log = LogFactory.getLog(LogHandler.class.getName()); long start = -1; private boolean writeToConsole = false; private String filename = "axis.log"; public void init() { super.init(); Object opt = this.getOption("LogHandler.writeToConsole"); if (opt != null && opt instanceof String && "true".equalsIgnoreCase((String)opt)) writeToConsole = true; opt = this.getOption("LogHandler.fileName"); if (opt != null && opt instanceof String) filename = (String)opt; } public void invoke(MessageContext msgContext) throws AxisFault { log.debug("Enter: LogHandler::invoke"); if (msgContext.getPastPivot() == false) { start = System.currentTimeMillis(); } else { logMessages(msgContext); } log.debug("Exit: LogHandler::invoke"); } private void logMessages(MessageContext msgContext) throws AxisFault { try { PrintWriter writer = null; writer = getWriter(); Message inMsg = msgContext.getRequestMessage(); Message outMsg = msgContext.getResponseMessage(); writer.println( "=======================================================" ); if (start != -1) { writer.println( "= " + Messages.getMessage("elapsed00", "" + (System.currentTimeMillis() - start))); } writer.println( "= " + Messages.getMessage("inMsg00", (inMsg == null ? "null" : inMsg.getSOAPPartAsString()))); writer.println( "= " + Messages.getMessage("outMsg00", (outMsg == null ? "null" : outMsg.getSOAPPartAsString()))); writer.println( "=======================================================" ); //START FIX: http://nagoya.apache.org/bugzilla/show_bug.cgi?id=16646 if (!writeToConsole) { writer.close(); } //END FIX: http://nagoya.apache.org/bugzilla/show_bug.cgi?id=16646 } catch( Exception e ) { log.error( Messages.getMessage("exception00"), e ); throw AxisFault.makeFault(e); } } private PrintWriter getWriter() throws IOException { PrintWriter writer; // Allow config info to control where we write. if (writeToConsole) { // Writing to the console writer = new PrintWriter(System.out); } else { // Writing to a file. if (filename == null) { filename = "axis.log"; } writer = new PrintWriter(new FileWriter( filename, true )); } return writer; } public void onFault(MessageContext msgContext) { try { logMessages(msgContext); } catch (AxisFault axisFault) { log.error(Messages.getMessage("exception00"), axisFault); } } };
7,809
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/handlers/LogMessage.java
/* * Copyright 2001-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.axis.handlers; import org.apache.axis.MessageContext; import org.apache.axis.components.logger.LogFactory; import org.apache.commons.logging.Log; /** This handler simply prints a custom message to the debug log. * * @author Glen Daniels (gdaniels@apache.org) */ public class LogMessage extends BasicHandler { protected static Log log = LogFactory.getLog(LogMessage.class.getName()); public void invoke(MessageContext context) { String msg = (String)getOption("message"); if (msg != null) log.info(msg); } }
7,810
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/handlers/SimpleAuthorizationHandler.java
/* * Copyright 2001-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.axis.handlers ; import org.apache.axis.AxisFault; import org.apache.axis.Handler; import org.apache.axis.MessageContext; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.security.AuthenticatedUser; import org.apache.axis.security.SecurityProvider; import org.apache.axis.utils.JavaUtils; import org.apache.axis.utils.Messages; import org.apache.commons.logging.Log; import java.util.StringTokenizer; /** * Just a simple Authorization Handler to see if the user * specified in the Bag in the MessageContext is allowed to preform this * action. * * Look at the <code>allowedRoles</code> handler parameter to determine if * user has rights to access the service * * The <code>allowByDefault</code> handler parameter can be used to authorize * all users if the parameter is set to true and the <code>allowedRoles</code> * access control list is not specified. * * Replace this with your 'real' Authorization code. * * @author Doug Davis (dug@us.ibm.com) * @author Sam Ruby (rubys@us.ibm.com) */ public class SimpleAuthorizationHandler extends BasicHandler { protected static Log log = LogFactory.getLog(SimpleAuthorizationHandler.class.getName()); /** * Authorize the user and targetService from the msgContext */ public void invoke(MessageContext msgContext) throws AxisFault { if (log.isDebugEnabled()) { log.debug("Enter: SimpleAuthorizationHandler::invoke"); } boolean allowByDefault = JavaUtils.isTrueExplicitly(getOption("allowByDefault")); AuthenticatedUser user = (AuthenticatedUser)msgContext. getProperty(MessageContext.AUTHUSER); if (user == null) throw new AxisFault("Server.NoUser", Messages.getMessage("needUser00"), null, null); String userID = user.getName(); Handler serviceHandler = msgContext.getService(); if (serviceHandler == null) throw new AxisFault(Messages.getMessage("needService00")); String serviceName = serviceHandler.getName(); String allowedRoles = (String)serviceHandler.getOption("allowedRoles"); if (allowedRoles == null) { if (allowByDefault) { if (log.isDebugEnabled()) { log.debug(Messages.getMessage( "noRoles00")); } } else { if (log.isDebugEnabled()) { log.debug(Messages.getMessage( "noRoles01")); } throw new AxisFault( "Server.Unauthorized", Messages.getMessage("notAuth00", userID, serviceName), null, null ); } if (log.isDebugEnabled()) { log.debug("Exit: SimpleAuthorizationHandler::invoke"); } return; } SecurityProvider provider = (SecurityProvider)msgContext.getProperty(MessageContext.SECURITY_PROVIDER); if (provider == null) throw new AxisFault(Messages.getMessage("noSecurity00")); StringTokenizer st = new StringTokenizer(allowedRoles, ","); while (st.hasMoreTokens()) { String thisRole = st.nextToken(); if (provider.userMatches(user, thisRole)) { if (log.isDebugEnabled()) { log.debug(Messages.getMessage("auth01", userID, serviceName)); } if (log.isDebugEnabled()) { log.debug("Exit: SimpleAuthorizationHandler::invoke"); } return; } } throw new AxisFault( "Server.Unauthorized", Messages.getMessage("cantAuth02", userID, serviceName), null, null ); } /** * Nothing to undo */ public void onFault(MessageContext msgContext) { if (log.isDebugEnabled()) { log.debug("Enter: SimpleAuthorizationHandler::onFault"); log.debug("Exit: SimpleAuthorizationHandler::onFault"); } } };
7,811
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/handlers/ErrorHandler.java
/* * Copyright 2001-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.axis.handlers ; import org.apache.axis.AxisFault; import org.apache.axis.MessageContext; import org.apache.axis.components.logger.LogFactory; import org.apache.commons.logging.Log; /** * * @author Doug Davis (dug@us.ibm.com) * @author Glen Daniels (gdaniels@allaire.com) */ public class ErrorHandler extends BasicHandler { protected static Log log = LogFactory.getLog(ErrorHandler.class.getName()); public void invoke(MessageContext msgContext) throws AxisFault { log.debug("Enter: ErrorHandler::invoke"); throw new AxisFault( "Server.Whatever", "ERROR", null, null ); } };
7,812
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/handlers/MD5AttachHandler.java
/* * Copyright 2001-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.axis.handlers; import org.apache.axis.AxisFault; import org.apache.axis.Message; import org.apache.axis.MessageContext; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.soap.SOAPConstants; import org.apache.axis.utils.Messages; import org.apache.commons.logging.Log; /** * * @author Doug Davis (dug@us.ibm.com) * @author Rick Rineholt */ public class MD5AttachHandler extends org.apache.axis.handlers.BasicHandler { protected static Log log = LogFactory.getLog(MD5AttachHandler.class.getName()); public void invoke(MessageContext msgContext) throws AxisFault { log.debug("Enter: MD5AttachHandler::invoke"); try { // log.debug("IN MD5"); Message msg = msgContext.getRequestMessage(); SOAPConstants soapConstants = msgContext.getSOAPConstants(); org.apache.axis.message.SOAPEnvelope env = (org.apache.axis.message.SOAPEnvelope) msg.getSOAPEnvelope(); org.apache.axis.message.SOAPBodyElement sbe = env.getFirstBody();//env.getBodyByName("ns1", "addedfile"); org.w3c.dom.Element sbElement = sbe.getAsDOM(); //get the first level accessor ie parameter org.w3c.dom.Node n = sbElement.getFirstChild(); for (; n != null && !(n instanceof org.w3c.dom.Element); n = n.getNextSibling()); org.w3c.dom.Element paramElement = (org.w3c.dom.Element) n; //Get the href associated with the attachment. String href = paramElement.getAttribute(soapConstants.getAttrHref()); org.apache.axis.Part ap = msg.getAttachmentsImpl().getAttachmentByReference(href); javax.activation.DataHandler dh = org.apache.axis.attachments.AttachmentUtils.getActivationDataHandler(ap); org.w3c.dom.Node timeNode = paramElement.getFirstChild(); long startTime = -1; if (timeNode != null && timeNode instanceof org.w3c.dom.Text) { String startTimeStr = ((org.w3c.dom.Text) timeNode).getData(); startTime = Long.parseLong(startTimeStr); } // log.debug("GOTIT"); long receivedTime = System.currentTimeMillis(); long elapsedTime = -1; // log.debug("startTime=" + startTime); // log.debug("receivedTime=" + receivedTime); if (startTime > 0) elapsedTime = receivedTime - startTime; String elapsedTimeStr = elapsedTime + ""; // log.debug("elapsedTimeStr=" + elapsedTimeStr); java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5"); java.io.InputStream attachmentStream = dh.getInputStream(); int bread = 0; byte[] buf = new byte[64 * 1024]; do { bread = attachmentStream.read(buf); if (bread > 0) { md.update(buf, 0, bread); } } while (bread > -1); attachmentStream.close(); buf = null; //Add the mime type to the digest. String contentType = dh.getContentType(); if (contentType != null && contentType.length() != 0) { md.update( contentType.getBytes("US-ASCII")); } sbe = env.getFirstBody(); sbElement = sbe.getAsDOM(); //get the first level accessor ie parameter n = sbElement.getFirstChild(); for (; n != null && !(n instanceof org.w3c.dom.Element); n = n.getNextSibling()); paramElement = (org.w3c.dom.Element) n; // paramElement.setAttribute(soapConstants.getAttrHref(), respHref); String MD5String = org.apache.axis.encoding.Base64.encode(md.digest()); String senddata = " elapsedTime=" + elapsedTimeStr + " MD5=" + MD5String; // log.debug("senddata=" + senddata); paramElement.appendChild( paramElement.getOwnerDocument().createTextNode(senddata)); sbe = new org.apache.axis.message.SOAPBodyElement(sbElement); env.clearBody(); env.addBodyElement(sbe); msg = new Message( env ); msgContext.setResponseMessage( msg ); } catch ( Exception e ) { log.error( Messages.getMessage("exception00"), e ); throw AxisFault.makeFault(e); } log.debug("Exit: MD5AttachHandler::invoke"); } }
7,813
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/handlers/SimpleSessionHandler.java
/* * Copyright 2001-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.axis.handlers; import org.apache.axis.AxisEngine; import org.apache.axis.AxisFault; import org.apache.axis.Constants; import org.apache.axis.Message; import org.apache.axis.MessageContext; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.message.SOAPEnvelope; import org.apache.axis.message.SOAPHeaderElement; import org.apache.axis.session.SimpleSession; import org.apache.axis.utils.Messages; import org.apache.axis.utils.SessionUtils; import org.apache.commons.logging.Log; import javax.xml.namespace.QName; import javax.xml.rpc.server.ServiceLifecycle; import java.util.Enumeration; import java.util.HashSet; import java.util.Hashtable; import java.util.Iterator; import java.util.Map; import java.util.Set; /** This handler uses SOAP headers to do simple session management. * * <p>Essentially, you install it on both the request and response chains of * your service, on both the client and the server side.</p> * * <p>ON THE SERVER:</p> * <ul> * <li>The REQUEST is checked for a session ID header. If present, we * look up the correct SimpleSession. If not, we create a new session. * In either case, we install the session into the MessageContext, and * put its ID in the SESSION_ID property. * <li>The RESPONSE gets a session ID header tacked on, assuming we found a * SESSION_ID property in the MessageContext. * </ul> * <p>ON THE CLIENT:</p> * <ul> * <li>The RESPONSE messages are checked for session ID headers. If present, * we pull the ID out and insert it into an option in the AxisClient. * This works because a given Call object is associated with a single * AxisClient. However, we might want to find a way to put it into the * Call object itself, which would make a little more sense. This would * mean being able to get to the Call from the MC, i.e. adding a getCall() * API (which would only work on the client side).... * <li>When REQUESTS are generated, we look to see if an ID option is present * in the AxisClient associated with the MessageContext. If so, we * insert a session ID header with the appropriate ID. * </ul> * * <p>SimpleSessions are "reaped" periodically via a very simplistic * mechanism. Each time the handler is invoke()d we check to see if more * than <b>reapPeriodicity</b> milliseconds have elapsed since the last * reap. If so, we walk the collection of active Sessions, and for each * one, if it hasn't been "touched" (i.e. had a getProperty() or setProperty() * performed) in longer than its timeout, we remove it from the collection.</p> * * @author Glen Daniels (gdaniels@apache.org) */ public class SimpleSessionHandler extends BasicHandler { protected static Log log = LogFactory.getLog(SimpleSessionHandler.class.getName()); public static final String SESSION_ID = "SimpleSession.id"; public static final String SESSION_NS = "http://xml.apache.org/axis/session"; public static final String SESSION_LOCALPART = "sessionID"; public static final QName sessionHeaderName = new QName(SESSION_NS, SESSION_LOCALPART); private Hashtable activeSessions = new Hashtable(); // Reap timed-out sessions on the first request after this many // seconds. private long reapPeriodicity = 30; private long lastReapTime = 0; // By default, sessions time out after 1 minute of inactivity (60 sec) private int defaultSessionTimeout = 60; /** * Process a MessageContext. */ public void invoke(MessageContext context) throws AxisFault { // Should we reap timed out sessions? long curTime = System.currentTimeMillis(); boolean reap = false; // Minimize synchronicity, just check in here, do reap later. synchronized (this) { if (curTime > lastReapTime + (reapPeriodicity * 1000)) { reap = true; lastReapTime = curTime; } } if (reap) { Set entries = activeSessions.entrySet(); Set victims = new HashSet(); Object key; Iterator i; for (i = entries.iterator(); i.hasNext();) { Map.Entry entry = (Map.Entry) i.next(); key = entry.getKey(); SimpleSession session = (SimpleSession) entry.getValue(); if ((curTime - session.getLastAccessTime()) > (session.getTimeout() * 1000)) { log.debug(Messages.getMessage("timeout00", key.toString())); // Don't modify the hashtable while we're iterating. victims.add(key); } } // Now go remove all the victims we found during the iteration. for (i = victims.iterator(); i.hasNext();) { key = i.next(); SimpleSession session = (SimpleSession)activeSessions.get(key); activeSessions.remove(key); // For each victim, swing through the data looking for // ServiceLifecycle objects, and calling destroy() on them. // FIXME : This cleanup should probably happen on another // thread, as it might take a little while. Enumeration keys = session.getKeys(); while (keys != null && keys.hasMoreElements()) { String keystr = (String)keys.nextElement(); Object obj = session.get(keystr); if (obj != null && obj instanceof ServiceLifecycle) { ((ServiceLifecycle)obj).destroy(); } } } } if (context.isClient()) { doClient(context); } else { doServer(context); } } /** * Client side of processing. */ public void doClient(MessageContext context) throws AxisFault { if (context.getPastPivot()) { // This is a response. Check it for the session header. Message msg = context.getResponseMessage(); if (msg == null) return; SOAPEnvelope env = msg.getSOAPEnvelope(); SOAPHeaderElement header = env.getHeaderByName(SESSION_NS, SESSION_LOCALPART); if (header == null) return; // Got one! try { Long id = (Long)header. getValueAsType(Constants.XSD_LONG); // Store it away. AxisEngine engine = context.getAxisEngine(); engine.setOption(SESSION_ID, id); // Note that we processed this header! header.setProcessed(true); } catch (Exception e) { throw AxisFault.makeFault(e); } } else { AxisEngine engine = context.getAxisEngine(); Long id = (Long)engine.getOption(SESSION_ID); if (id == null) return; // We have a session ID, so insert the header Message msg = context.getRequestMessage(); if (msg == null) throw new AxisFault(Messages.getMessage("noRequest00")); SOAPEnvelope env = msg.getSOAPEnvelope(); SOAPHeaderElement header = new SOAPHeaderElement(SESSION_NS, SESSION_LOCALPART, id); env.addHeader(header); } } /** * Server side of processing. */ public void doServer(MessageContext context) throws AxisFault { if (context.getPastPivot()) { // This is a response. Add the session header if we have an // ID. Long id = (Long)context.getProperty(SESSION_ID); if (id == null) return; Message msg = context.getResponseMessage(); if (msg == null) return; SOAPEnvelope env = msg.getSOAPEnvelope(); SOAPHeaderElement header = new SOAPHeaderElement(SESSION_NS, SESSION_LOCALPART, id); env.addHeader(header); } else { // Request. Set up the session if we find the header. Message msg = context.getRequestMessage(); if (msg == null) throw new AxisFault(Messages.getMessage("noRequest00")); SOAPEnvelope env = msg.getSOAPEnvelope(); SOAPHeaderElement header = env.getHeaderByName(SESSION_NS, SESSION_LOCALPART); Long id; if (header != null) { // Got one! try { id = (Long)header. getValueAsType(Constants.XSD_LONG); } catch (Exception e) { throw AxisFault.makeFault(e); } } else { id = getNewSession(); } SimpleSession session = (SimpleSession)activeSessions.get(id); if (session == null) { // Must have timed out, get a new one. id = getNewSession(); session = (SimpleSession)activeSessions.get(id); } // This session is still active... session.touch(); // Store it away in the MessageContext. context.setSession(session); context.setProperty(SESSION_ID, id); } } /** * Generate a new session, register it, and return its ID. * * @return the new session's ID for later lookup. */ private synchronized Long getNewSession() { Long id = SessionUtils.generateSession(); SimpleSession session = new SimpleSession(); session.setTimeout(defaultSessionTimeout); activeSessions.put(id, session); return id; } /** * Set the reaper periodicity in SECONDS * * Convenience method for testing. * * !!! TODO: Should be able to set this via options on the Handler * or perhaps the engine. */ public void setReapPeriodicity(long reapTime) { reapPeriodicity = reapTime; } /** * Set the default session timeout in SECONDS * * Again, for testing. */ public void setDefaultSessionTimeout(int defaultSessionTimeout) { this.defaultSessionTimeout = defaultSessionTimeout; } }
7,814
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/handlers/HandlerInfoChainFactory.java
/* * Copyright 2001-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.axis.handlers; import javax.xml.rpc.handler.HandlerChain; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.io.Serializable; public class HandlerInfoChainFactory implements Serializable { protected List handlerInfos = new ArrayList(); protected String[] _roles = null; public HandlerInfoChainFactory() { } public HandlerInfoChainFactory(List handlerInfos) { this.handlerInfos = handlerInfos; } public List getHandlerInfos() { return this.handlerInfos; } public HandlerChain createHandlerChain() { HandlerChain hc = new HandlerChainImpl(handlerInfos); hc.setRoles(getRoles()); return hc; } public String[] getRoles() { return _roles; } public void setRoles(String[] roles) { _roles = roles; } public void init(Map map) { // DO SOMETHING WITH THIS } }
7,815
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/handlers/HandlerChainImpl.java
/* * Copyright 2001-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.axis.handlers; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.utils.ClassUtils; import org.apache.axis.utils.Messages; import org.apache.commons.logging.Log; import javax.xml.rpc.JAXRPCException; import javax.xml.rpc.handler.Handler; import javax.xml.rpc.handler.HandlerInfo; import javax.xml.rpc.handler.MessageContext; import javax.xml.rpc.handler.soap.SOAPMessageContext; import javax.xml.rpc.soap.SOAPFaultException; import javax.xml.soap.SOAPBody; import javax.xml.soap.SOAPElement; import javax.xml.soap.SOAPEnvelope; import javax.xml.soap.SOAPException; import javax.xml.soap.SOAPMessage; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.Map; /** * Implementation of HandlerChain */ public class HandlerChainImpl extends ArrayList implements javax.xml.rpc.handler .HandlerChain { protected static Log log = LogFactory.getLog(HandlerChainImpl.class.getName()); public static final String JAXRPC_METHOD_INFO = "jaxrpc.method.info"; private String[] _roles; private int falseIndex = -1; public String[] getRoles() { return _roles; } public void setRoles(String[] roles) { if (roles != null) { // use clone for cheap array copy _roles = (String[])roles.clone(); } } public void init(Map map) { // DO SOMETHING WITH THIS } protected List handlerInfos = new ArrayList(); public HandlerChainImpl() { } public HandlerChainImpl(List handlerInfos) { this.handlerInfos = handlerInfos; for (int i = 0; i < handlerInfos.size(); i++) { add(newHandler(getHandlerInfo(i))); } } public void addNewHandler(String className, Map config) { try { HandlerInfo handlerInfo = new HandlerInfo(ClassUtils.forName(className), config, null); handlerInfos.add(handlerInfo); add(newHandler(handlerInfo)); } catch (Exception ex) { String messageText = Messages.getMessage("NoJAXRPCHandler00", className); throw new JAXRPCException(messageText, ex); } } public boolean handleFault(MessageContext _context) { SOAPMessageContext context = (SOAPMessageContext)_context; preInvoke(context); try { int endIdx = size() - 1; if (falseIndex != -1) { endIdx = falseIndex; } for (int i = endIdx; i >= 0; i--) { if (getHandlerInstance(i).handleFault(context) == false) { return false; } } return true; } finally { postInvoke(context); } } public ArrayList getMessageInfo(SOAPMessage message) { ArrayList list = new ArrayList(); try { if(message == null || message.getSOAPPart() == null) return list; SOAPEnvelope env = message.getSOAPPart().getEnvelope(); SOAPBody body = env.getBody(); Iterator it = body.getChildElements(); SOAPElement operation = (SOAPElement)it.next(); list.add(operation.getElementName().toString()); for (Iterator i = operation.getChildElements(); i.hasNext();) { SOAPElement elt = (SOAPElement)i.next(); list.add(elt.getElementName().toString()); } } catch (Exception e) { log.debug("Exception in getMessageInfo : ", e); } return list; } public boolean handleRequest(MessageContext _context) { org.apache.axis.MessageContext actx = (org.apache.axis.MessageContext)_context; actx.setRoles(getRoles()); SOAPMessageContext context = (SOAPMessageContext)_context; preInvoke(context); try { for (int i = 0; i < size(); i++) { Handler currentHandler = getHandlerInstance(i); try { if (currentHandler.handleRequest(context) == false) { falseIndex = i; return false; } } catch (SOAPFaultException sfe) { falseIndex = i; throw sfe; } } return true; } finally { postInvoke(context); } } public boolean handleResponse(MessageContext context) { SOAPMessageContext scontext = (SOAPMessageContext)context; preInvoke(scontext); try { int endIdx = size() - 1; if (falseIndex != -1) { endIdx = falseIndex; } for (int i = endIdx; i >= 0; i--) { if (getHandlerInstance(i).handleResponse(context) == false) { return false; } } return true; } finally { postInvoke(scontext); } } private void preInvoke(SOAPMessageContext msgContext) { try { SOAPMessage message = msgContext.getMessage(); // Ensure that message is already in the form we want if(message != null && message.getSOAPPart() != null) message.getSOAPPart().getEnvelope(); msgContext.setProperty(org.apache.axis.SOAPPart.ALLOW_FORM_OPTIMIZATION, Boolean.FALSE); msgContext.setProperty(JAXRPC_METHOD_INFO, getMessageInfo(message)); } catch (Exception e) { log.debug("Exception in preInvoke : ", e); throw new RuntimeException("Exception in preInvoke : " + e.toString()); } } private void postInvoke(SOAPMessageContext msgContext) { Boolean propFormOptimization = (Boolean)msgContext.getProperty(org.apache.axis.SOAPPart.ALLOW_FORM_OPTIMIZATION); if (propFormOptimization != null && !propFormOptimization.booleanValue()) { msgContext.setProperty(org.apache.axis.SOAPPart.ALLOW_FORM_OPTIMIZATION, Boolean.TRUE); SOAPMessage message = msgContext.getMessage(); ArrayList oldList = (ArrayList)msgContext.getProperty(JAXRPC_METHOD_INFO); if (oldList != null) { if (!Arrays.equals(oldList.toArray(), getMessageInfo(message) .toArray())) { throw new RuntimeException(Messages.getMessage("invocationArgumentsModified00")); } } try { if (message != null) { message.saveChanges(); } } catch (SOAPException e) { log.debug("Exception in postInvoke : ", e); throw new RuntimeException("Exception in postInvoke : " + e.toString()); } } } public void destroy() { int endIdx = size() - 1; if (falseIndex != -1) { endIdx = falseIndex; } for (int i = endIdx; i >= 0; i--) { getHandlerInstance(i).destroy(); } falseIndex = -1; clear(); } private Handler getHandlerInstance(int index) { return (Handler)get(index); } private HandlerInfo getHandlerInfo(int index) { return (HandlerInfo)handlerInfos.get(index); } private Handler newHandler(HandlerInfo handlerInfo) { try { Handler handler = (Handler)handlerInfo.getHandlerClass() .newInstance(); handler.init(handlerInfo); return handler; } catch (Exception ex) { String messageText = Messages.getMessage("NoJAXRPCHandler00", handlerInfo.getHandlerClass().toString()); throw new JAXRPCException(messageText, ex); } } }
7,816
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/handlers
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/handlers/soap/MustUnderstandChecker.java
/* * Copyright 2001-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.axis.handlers.soap; import org.apache.axis.AxisFault; import org.apache.axis.Constants; import org.apache.axis.MessageContext; import org.apache.axis.Message; import org.apache.axis.description.OperationDesc; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.handlers.BasicHandler; import org.apache.axis.message.SOAPEnvelope; import org.apache.axis.message.SOAPHeaderElement; import org.apache.axis.soap.SOAPConstants; import org.apache.axis.utils.Messages; import org.apache.commons.logging.Log; import javax.xml.namespace.QName; import java.util.ArrayList; import java.util.Enumeration; import java.util.Vector; /** * MustUnderstandChecker is used to inject SOAP semantics just before * the pivot handler. */ public class MustUnderstandChecker extends BasicHandler { private static Log log = LogFactory.getLog(MustUnderstandChecker.class.getName()); private SOAPService service = null; public MustUnderstandChecker(SOAPService service) { this.service = service; } public void invoke(MessageContext msgContext) throws AxisFault { // Do SOAP semantics here if (log.isDebugEnabled()) { log.debug(Messages.getMessage("semanticCheck00")); } Message msg = msgContext.getCurrentMessage(); if (msg == null) return; // nothing to do if there's no message SOAPEnvelope env = msg.getSOAPEnvelope(); Vector headers = null; if (service != null) { ArrayList acts = service.getActors(); headers = env.getHeadersByActor(acts); } else { headers = env.getHeaders(); } // 1. Check mustUnderstands Vector misunderstoodHeaders = null; Enumeration enumeration = headers.elements(); while (enumeration.hasMoreElements()) { SOAPHeaderElement header = (SOAPHeaderElement) enumeration. nextElement(); // Ignore header, if it is a parameter to the operation if(msgContext != null && msgContext.getOperation() != null) { OperationDesc oper = msgContext.getOperation(); if(oper.getParamByQName(header.getQName())!=null) { continue; } } if (header.getMustUnderstand() && !header.isProcessed()) { if (misunderstoodHeaders == null) misunderstoodHeaders = new Vector(); misunderstoodHeaders.addElement(header); } } SOAPConstants soapConstants = msgContext.getSOAPConstants(); // !!! we should indicate SOAP1.2 compliance via the // MessageContext, not a boolean here.... if (misunderstoodHeaders != null) { AxisFault fault = new AxisFault(soapConstants.getMustunderstandFaultQName(), null, null, null, null, null); StringBuffer whatWasMissUnderstood = new StringBuffer(256); enumeration = misunderstoodHeaders.elements(); while (enumeration.hasMoreElements()) { SOAPHeaderElement badHeader = (SOAPHeaderElement) enumeration. nextElement(); QName badQName = new QName(badHeader.getNamespaceURI(), badHeader.getName()); if (whatWasMissUnderstood.length() != 0) whatWasMissUnderstood.append(", "); whatWasMissUnderstood.append(badQName.toString()); // !!! If SOAP 1.2, insert misunderstood fault headers here if ( soapConstants == SOAPConstants.SOAP12_CONSTANTS ) { SOAPHeaderElement newHeader = new SOAPHeaderElement(Constants.URI_SOAP12_ENV, Constants.ELEM_NOTUNDERSTOOD); newHeader.addAttribute(null, Constants.ATTR_QNAME, badQName); fault.addHeader(newHeader); } } fault.setFaultString(Messages.getMessage("noUnderstand00", whatWasMissUnderstood.toString())); throw fault; } } }
7,817
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/handlers
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/handlers/soap/SOAPService.java
/* * Copyright 2001-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.axis.handlers.soap; import org.apache.axis.AxisEngine; import org.apache.axis.AxisFault; import org.apache.axis.Constants; import org.apache.axis.Handler; import org.apache.axis.Message; import org.apache.axis.MessageContext; import org.apache.axis.SimpleTargetedChain; import org.apache.axis.attachments.Attachments; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.description.JavaServiceDesc; import org.apache.axis.description.ServiceDesc; import org.apache.axis.encoding.TypeMappingRegistry; import org.apache.axis.constants.Style; import org.apache.axis.constants.Use; import org.apache.axis.handlers.HandlerChainImpl; import org.apache.axis.handlers.HandlerInfoChainFactory; import org.apache.axis.message.SOAPEnvelope; import org.apache.axis.message.SOAPFault; import org.apache.axis.providers.BasicProvider; import org.apache.axis.utils.LockableHashtable; import org.apache.axis.utils.Messages; import org.apache.axis.utils.XMLUtils; import org.apache.axis.utils.ClassUtils; import org.apache.commons.logging.Log; import org.w3c.dom.Document; import javax.xml.rpc.soap.SOAPFaultException; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Hashtable; import java.util.Vector; import java.util.Map; import java.util.HashMap; import java.util.List; /** A <code>SOAPService</code> is a Handler which encapsulates a SOAP * invocation. It has an request chain, an response chain, and a pivot-point, * and handles the SOAP semantics when invoke()d. * * @author Glen Daniels (gdaniels@apache.org) * @author Doug Davis (dug@us.ibm.com) */ public class SOAPService extends SimpleTargetedChain { private static Log log = LogFactory.getLog(SOAPService.class.getName()); /** Valid transports for this service * (server side only!) * * !!! For now, if this is null, we assume all * transports are valid. */ private Vector validTransports = null; /** * Does this service require a high-fidelity SAX recording of messages? * (default is true) */ private boolean highFidelityRecording = true; /** * How does this service wish data which would normally be sent as * an attachment to be sent? Default for requests is * org.apache.axis.attachments.Attachments.SEND_TYPE_DEFAULT, * and the default for responses is to match the request. */ private int sendType = Attachments.SEND_TYPE_NOTSET; /** * Our ServiceDescription. Holds pretty much all the interesting * metadata about this service. */ private ServiceDesc serviceDescription = new JavaServiceDesc(); private AxisEngine engine; /** * A list of our active service objects (these can have lifetimes and * be reaped) */ public Map serviceObjects = new HashMap(); public int nextObjectID = 1; private boolean isRunning = true; /** * Actor list - these are just the service-specific ones */ ArrayList actors = new ArrayList(); /** * Get the service-specific actor list * @return */ public ArrayList getServiceActors() { return actors; } /** * Get the merged actor list for this service, including engine-wide * actor URIs. * * @return */ public ArrayList getActors() { ArrayList acts = (ArrayList)actors.clone(); // ??? cache this? if (engine != null) { acts.addAll(engine.getActorURIs()); } return acts; } public List getRoles() { return getActors(); } /** * Set the service-specific role list * * @param roles a List of Strings, each containing a role URI */ public void setRoles(List roles) { actors = new ArrayList(roles); } /** Standard, no-arg constructor. */ public SOAPService() { setOptionsLockable(true); initHashtable(); // For now, always assume we're the ultimate destination. actors.add(""); } /** Constructor with real or null request, pivot, and response * handlers. A special request handler is specified to inject * SOAP semantics. */ public SOAPService(Handler reqHandler, Handler pivHandler, Handler respHandler) { this(); init(reqHandler, new MustUnderstandChecker(this), pivHandler, null, respHandler); } public TypeMappingRegistry getTypeMappingRegistry() { return serviceDescription.getTypeMappingRegistry(); } /** Convenience constructor for wrapping SOAP semantics around * "service handlers" which actually do work. */ public SOAPService(Handler serviceHandler) { this(); init(null, new MustUnderstandChecker(this), serviceHandler, null, null); } /** Tell this service which engine it's deployed to. * */ public void setEngine(AxisEngine engine) { if (engine == null) throw new IllegalArgumentException( Messages.getMessage("nullEngine")); this.engine = engine; ((LockableHashtable)options).setParent(engine.getOptions()); TypeMappingRegistry tmr = engine.getTypeMappingRegistry(); getTypeMappingRegistry().delegate(tmr); } public AxisEngine getEngine() { return engine; } public boolean availableFromTransport(String transportName) { if (validTransports != null) { for (int i = 0; i < validTransports.size(); i++) { if (validTransports.elementAt(i).equals(transportName)) return true; } return false; } return true; } public Style getStyle() { return serviceDescription.getStyle(); } public void setStyle(Style style) { serviceDescription.setStyle(style); } public Use getUse() { return serviceDescription.getUse(); } public void setUse(Use style) { serviceDescription.setUse(style); } public ServiceDesc getServiceDescription() { return serviceDescription; } /** * Returns a service description with the implementation class filled in. * Syncronized to prevent simutaneous modification of serviceDescription. */ public synchronized ServiceDesc getInitializedServiceDesc( MessageContext msgContext) throws AxisFault { if (!serviceDescription.isInitialized()) { // Let the provider do the work of filling in the service // descriptor. This is so that it can decide itself how best // to map the Operations. In the future, we may want to support // providers which don't strictly map to Java class backends // (BSFProvider, etc.), and as such we hand off here. if (pivotHandler instanceof BasicProvider) { ((BasicProvider)pivotHandler).initServiceDesc(this, msgContext); } } return serviceDescription; } public void setServiceDescription(ServiceDesc serviceDescription) { if (serviceDescription == null) { // FIXME: Throw NPE? return; } this.serviceDescription = serviceDescription; //serviceDescription.setTypeMapping((TypeMapping)this.getTypeMappingRegistry().getDefaultTypeMapping()); } public void setPropertyParent(Hashtable parent) { if (options == null) { options = new LockableHashtable(); } ((LockableHashtable)options).setParent(parent); } /** * Generate WSDL. If we have a specific file configured in the * ServiceDesc, just return that. Otherwise run through all the Handlers * (including the provider) and call generateWSDL() on them via our * parent's implementation. */ public void generateWSDL(MessageContext msgContext) throws AxisFault { if (serviceDescription == null || serviceDescription.getWSDLFile() == null) { super.generateWSDL(msgContext); return; } InputStream instream = null; // Got a WSDL file in the service description, so try and read it try { String filename= serviceDescription.getWSDLFile(); File file=new File(filename); if(file.exists()) { //if this resolves to a file, load it instream = new FileInputStream(filename); } else if(msgContext.getStrProp(Constants.MC_HOME_DIR)!=null){ String path = msgContext.getStrProp(Constants.MC_HOME_DIR) +'/' + filename; file = new File(path); if(file.exists()) { //if this resolves to a file, load it instream = new FileInputStream(path); } } if(instream == null) { //else load a named resource in our classloader. instream = ClassUtils.getResourceAsStream(this.getClass(),filename); if (instream == null) { String errorText=Messages.getMessage("wsdlFileMissing",filename); throw new AxisFault(errorText); } } Document doc = XMLUtils.newDocument(instream); msgContext.setProperty("WSDL", doc); } catch (Exception e) { throw AxisFault.makeFault(e); } finally { if(instream!=null) { try { instream.close(); } catch (IOException e) { } } } } /********************************************************************* * Administration and management APIs * * These can get called by various admin adapters, such as JMX MBeans, * our own Admin client, web applications, etc... * ********************************************************************* */ /** Placeholder for "resume this service" method */ public void start() { isRunning = true; } /** Placeholder for "suspend this service" method */ public void stop() { isRunning = false; } /** * Is this service suspended? * @return */ public boolean isRunning() { return isRunning; } /** * Make this service available on a particular transport */ public void enableTransport(String transportName) { if (log.isDebugEnabled()) { log.debug(Messages.getMessage( "enableTransport00", "" + this, transportName)); } if (validTransports == null) validTransports = new Vector(); validTransports.addElement(transportName); } /** * Disable access to this service from a particular transport */ public void disableTransport(String transportName) { if (validTransports != null) { validTransports.removeElement(transportName); } } public boolean needsHighFidelityRecording() { return highFidelityRecording; } public void setHighFidelityRecording(boolean highFidelityRecording) { this.highFidelityRecording = highFidelityRecording; } // see org.apache.axis.attachments.Attachments public int getSendType() { return sendType; } public void setSendType(int sendType) { this.sendType = sendType; } public void invoke(MessageContext msgContext) throws AxisFault { HandlerInfoChainFactory handlerFactory = (HandlerInfoChainFactory) this.getOption(Constants.ATTR_HANDLERINFOCHAIN); HandlerChainImpl handlerImpl = null; if (handlerFactory != null) handlerImpl = (HandlerChainImpl) handlerFactory.createHandlerChain(); boolean result = true; try { if (handlerImpl != null) { try { result = handlerImpl.handleRequest(msgContext); } catch (SOAPFaultException e) { msgContext.setPastPivot(true); handlerImpl.handleFault(msgContext); return; } } if (result) { try { super.invoke(msgContext); } catch (AxisFault e) { msgContext.setPastPivot(true); if (handlerImpl != null) { handlerImpl.handleFault(msgContext); } throw e; } } else { msgContext.setPastPivot(true); } if ( handlerImpl != null) { handlerImpl.handleResponse(msgContext); } } catch (SOAPFaultException e) { msgContext.setPastPivot(true); throw AxisFault.makeFault(e); } catch (RuntimeException e) { SOAPFault fault = new SOAPFault(new AxisFault("Server", "Server Error", null, null)); SOAPEnvelope env = new SOAPEnvelope(); env.addBodyElement(fault); Message message = new Message(env); message.setMessageType(Message.RESPONSE); msgContext.setResponseMessage(message); throw AxisFault.makeFault(e); } finally { if (handlerImpl != null) { handlerImpl.destroy(); } } } }
7,818
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/handlers
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/handlers/http/URLMapper.java
/* * Copyright 2001-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.axis.handlers.http; import org.apache.axis.AxisFault; import org.apache.axis.MessageContext; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.handlers.BasicHandler; import org.apache.axis.transport.http.HTTPConstants; import org.apache.commons.logging.Log; /** An <code>URLMapper</code> attempts to use the extra path info * of this request as the service name. * * @author Glen Daniels (gdaniels@apache.org) */ public class URLMapper extends BasicHandler { protected static Log log = LogFactory.getLog(URLMapper.class.getName()); public void invoke(MessageContext msgContext) throws AxisFault { log.debug("Enter: URLMapper::invoke"); /** If there's already a targetService then just return. */ if ( msgContext.getService() == null ) { // path may or may not start with a "/". see http://issues.apache.org/jira/browse/AXIS-1372 String path = (String)msgContext.getProperty(HTTPConstants.MC_HTTP_SERVLETPATHINFO); if ((path != null) && (path.length() >= 1)) { //rules out the cases of path="", path=null if(path.startsWith("/")) path = path.substring(1); //chop the extra "/" msgContext.setTargetService( path ); } } log.debug("Exit: URLMapper::invoke"); } public void generateWSDL(MessageContext msgContext) throws AxisFault { invoke(msgContext); } }
7,819
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/handlers
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/handlers/http/HTTPActionHandler.java
/* * Copyright 2001-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.axis.handlers.http; import org.apache.axis.AxisFault; import org.apache.axis.MessageContext; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.handlers.BasicHandler; import org.apache.axis.utils.Messages; import org.apache.commons.logging.Log; /** An <code>HTTPActionHandler</code> simply sets the context's TargetService * property from the HTTPAction property. We expect there to be a * Router on the chain after us, to dispatch to the service named in * the SOAPAction. * * In the real world, this might do some more complex mapping of * SOAPAction to a TargetService. * * @author Glen Daniels (gdaniels@allaire.com) * @author Doug Davis (dug@us.ibm.com) */ public class HTTPActionHandler extends BasicHandler { protected static Log log = LogFactory.getLog(HTTPActionHandler.class.getName()); public void invoke(MessageContext msgContext) throws AxisFault { log.debug("Enter: HTTPActionHandler::invoke"); /** If there's already a targetService then just return. */ if ( msgContext.getService() == null ) { String action = (String) msgContext.getSOAPActionURI(); log.debug( " HTTP SOAPAction: " + action ); /** The idea is that this handler only goes in the chain IF this * service does a mapping between SOAPAction and target. Therefore * if we get here with no action, we're in trouble. */ if (action == null) { throw new AxisFault( "Server.NoHTTPSOAPAction", Messages.getMessage("noSOAPAction00"), null, null ); } action = action.trim(); // handle empty SOAPAction if (action.length() > 0 && action.charAt(0) == '\"') { // assertTrue(action.endsWith("\"") if (action.equals("\"\"")) { action = ""; } else { action = action.substring(1, action.length() - 1); } } // if action is zero-length string, don't set anything if (action.length() > 0) { msgContext.setTargetService( action ); } } log.debug("Exit: HTTPActionHandler::invoke"); } }
7,820
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/handlers
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/handlers/http/HTTPAuthHandler.java
/* * Copyright 2001-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.axis.handlers.http; import org.apache.axis.AxisFault; import org.apache.axis.MessageContext; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.encoding.Base64; import org.apache.axis.handlers.BasicHandler; import org.apache.axis.transport.http.HTTPConstants; import org.apache.axis.utils.Messages; import org.apache.commons.logging.Log; /** An <code>HTTPAuthHandler</code> simply sets the context's username * and password properties from the HTTP auth headers. * * @author Glen Daniels (gdaniels@allaire.com) * @author Doug Davis (dug@us.ibm.com) */ public class HTTPAuthHandler extends BasicHandler { protected static Log log = LogFactory.getLog(HTTPAuthHandler.class.getName()); public void invoke(MessageContext msgContext) throws AxisFault { log.debug("Enter: HTTPAuthHandler::invoke"); /* Process the Basic Auth stuff in the headers */ /***********************************************/ String tmp = (String)msgContext.getProperty(HTTPConstants.HEADER_AUTHORIZATION); if ( tmp != null ) tmp = tmp.trim(); if ( tmp != null && tmp.startsWith("Basic ") ) { String user=null ; int i ; tmp = new String( Base64.decode( tmp.substring(6) ) ); i = tmp.indexOf( ':' ); if ( i == -1 ) user = tmp ; else user = tmp.substring( 0, i); msgContext.setUsername( user ); log.debug( Messages.getMessage("httpUser00", user) ); if ( i != -1 ) { String pwd = tmp.substring(i+1); if ( pwd != null && pwd.equals("") ) pwd = null ; if ( pwd != null ) { msgContext.setPassword( pwd ); log.debug( Messages.getMessage("httpPassword00", pwd) ); } } } log.debug("Exit: HTTPAuthHandler::invoke"); } }
7,821
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/session/Session.java
/* * Copyright 2001-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.axis.session; import java.util.Enumeration; /** * An abstract interface to provide session storage to Axis services. * * This is extremely basic at the moment. * * @author Glen Daniels (gdaniels@apache.org) */ public interface Session { /** Get a property from the session * * @param key the name of the property desired. */ public Object get(String key); /** Set a property in the session * * @param key the name of the property to set. * @param value the value of the property. */ public void set(String key, Object value); /** Remove a property from the session * * @param key the name of the property desired. */ public void remove(String key); /** * Get an enumeration of the keys in this session */ public Enumeration getKeys(); /** Set the session's time-to-live. * * This is implementation-specific, but basically should be the # * of seconds of inactivity which will cause the session to time * out and invalidate. "inactivity" is implementation-specific. */ public void setTimeout(int timeout); /** * Return the sessions' time-to-live. * * @return the timeout value for this session. */ public int getTimeout(); /** * "Touch" the session (mark it recently used) */ public void touch(); /** * invalidate the session */ public void invalidate(); /** * Get an Object suitable for synchronizing the session. This method * exists because different session implementations might provide * different ways of getting at shared data. For a simple hashtable- * based session, this would just be the hashtable, but for sessions * which use database connections, etc. it might be an object wrapping * a table ID or somesuch. */ public Object getLockObject(); }
7,822
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/session/SimpleSession.java
/* * Copyright 2001-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.axis.session; import java.util.Enumeration; import java.util.Hashtable; /** * A trivial session implementation. * * @author Glen Daniels (gdaniels@apache.org) */ public class SimpleSession implements Session { private Hashtable rep = null; /** Inactivity timeout (in seconds). * Not used yet. */ private int timeout = -1; private long lastTouched; /** * Default constructor - set lastTouched to now */ public SimpleSession() { lastTouched = System.currentTimeMillis(); } /** Get a property from the session * * @param key the name of the property desired. */ public Object get(String key) { if (rep == null) return null; lastTouched = System.currentTimeMillis(); return rep.get(key); } /** Set a property in the session * * @param key the name of the property to set. * @param value the value of the property. */ public void set(String key, Object value) { synchronized (this) { if (rep == null) rep = new Hashtable(); } lastTouched = System.currentTimeMillis(); rep.put(key, value); } /** Remove a property from the session * * @param key the name of the property desired. */ public void remove(String key) { if (rep != null) rep.remove(key); lastTouched = System.currentTimeMillis(); } /** * Get an enumeration of the keys in this session */ public Enumeration getKeys() { if (rep != null) return rep.keys(); return null; } /** Set the session's time-to-live. * * This is implementation-specific, but basically should be the # * of seconds of inactivity which will cause the session to time * out and invalidate. "inactivity" is implementation-specific. */ public void setTimeout(int timeout) { this.timeout = timeout; } public int getTimeout() { return timeout; } /** * "Touch" the session (mark it recently used) */ public void touch() { lastTouched = System.currentTimeMillis(); } /** * invalidate the session */ public void invalidate() { rep = null; lastTouched = System.currentTimeMillis(); timeout = -1; } public long getLastAccessTime() { return lastTouched; } /** * Get an Object suitable for synchronizing the session. This method * exists because different session implementations might provide * different ways of getting at shared data. For a simple hashtable- * based session, this would just be the hashtable, but for sessions * which use database connections, etc. it might be an object wrapping * a table ID or somesuch. */ public synchronized Object getLockObject() { if (rep == null) { rep = new Hashtable(); } return rep; } }
7,823
0
Create_ds/axis-axis1-java/axis-rt-management/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-management/src/main/java/org/apache/axis/management/ServiceAdmin.java
/* * Copyright 2003,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.axis.management; import org.apache.axis.AxisFault; import org.apache.axis.ConfigurationException; import org.apache.axis.EngineConfiguration; import org.apache.axis.WSDDEngineConfiguration; import org.apache.axis.deployment.wsdd.WSDDGlobalConfiguration; import org.apache.axis.deployment.wsdd.WSDDHandler; import org.apache.axis.deployment.wsdd.WSDDService; import org.apache.axis.deployment.wsdd.WSDDTransport; import org.apache.axis.description.ServiceDesc; import org.apache.axis.handlers.soap.SOAPService; import org.apache.axis.management.jmx.DeploymentAdministrator; import org.apache.axis.management.jmx.DeploymentQuery; import org.apache.axis.management.jmx.ServiceAdministrator; import org.apache.axis.server.AxisServer; import javax.xml.namespace.QName; import java.util.ArrayList; import java.util.Iterator; /** * The ServiceControl Object is responsible for starting and * stopping specific services * * @author bdillon * @version 1.0 */ public class ServiceAdmin { //Singleton AxisServer for Management static private AxisServer axisServer = null; /** * Start the Service * * @param serviceName * @throws AxisFault ConfigurationException */ static public void startService(String serviceName) throws AxisFault, ConfigurationException { AxisServer server = getEngine(); try { SOAPService service = server.getConfig().getService( new QName("", serviceName)); service.start(); } catch (ConfigurationException configException) { if (configException.getContainedException() instanceof AxisFault) { throw (AxisFault) configException.getContainedException(); } else { throw configException; } } } /** * Stop the Service * * @param serviceName * @throws AxisFault ConfigurationException */ static public void stopService(String serviceName) throws AxisFault, ConfigurationException { AxisServer server = getEngine(); try { SOAPService service = server.getConfig().getService( new QName("", serviceName)); service.stop(); } catch (ConfigurationException configException) { if (configException.getContainedException() instanceof AxisFault) { throw (AxisFault) configException.getContainedException();//Throw Axis fault if ist. of } else { throw configException; } } } /** * List all registered services * * @return Map of Services (SOAPService objects, Key is the ServiceName) * @throws AxisFault ConfigurationException */ static public String[] listServices() throws AxisFault, ConfigurationException { ArrayList list = new ArrayList(); AxisServer server = getEngine(); Iterator iter; // get list of ServiceDesc objects try { iter = server.getConfig().getDeployedServices(); } catch (ConfigurationException configException) { if (configException.getContainedException() instanceof AxisFault) { throw (AxisFault) configException.getContainedException();//Throw Axis fault if inst. of } else { throw configException; } } while (iter.hasNext()) { ServiceDesc sd = (ServiceDesc) iter.next(); String name = sd.getName(); list.add(name); } return (String[]) list.toArray(new String[list.size()]); } /** * Get the singleton engine for this management object * * @return * @throws AxisFault */ static public AxisServer getEngine() throws AxisFault { if (axisServer == null) { //Throw a could not get AxisEngine Exception throw new AxisFault( "Unable to locate AxisEngine for ServiceAdmin Object"); } return axisServer; } /** * Set the singleton engine * * @param axisSrv */ static public void setEngine(AxisServer axisSrv, String name) { ServiceAdmin.axisServer = axisSrv; Registrar.register(new ServiceAdministrator(), "axis:type=server", "ServiceAdministrator"); Registrar.register(new DeploymentAdministrator(), "axis:type=deploy", "DeploymentAdministrator"); Registrar.register(new DeploymentQuery(), "axis:type=query", "DeploymentQuery"); } static public void start() { if (axisServer != null) { axisServer.start(); } } static public void stop() { if (axisServer != null) { axisServer.stop(); } } static public void restart() { if (axisServer != null) { axisServer.stop(); axisServer.start(); } } static public void saveConfiguration() { if (axisServer != null) { axisServer.saveConfiguration(); } } static private WSDDEngineConfiguration getWSDDEngineConfiguration() { if (axisServer != null) { EngineConfiguration config = axisServer.getConfig(); if (config instanceof WSDDEngineConfiguration) { return (WSDDEngineConfiguration) config; } else { throw new RuntimeException("WSDDDeploymentHelper.getWSDDEngineConfiguration(): EngineConguration not of type WSDDEngineConfiguration"); } } return null; } static public void setGlobalConfig(WSDDGlobalConfiguration globalConfig) { getWSDDEngineConfiguration().getDeployment().setGlobalConfiguration(globalConfig); } static public WSDDGlobalConfiguration getGlobalConfig() { return getWSDDEngineConfiguration().getDeployment().getGlobalConfiguration(); } static public WSDDHandler getHandler(QName qname) { return getWSDDEngineConfiguration().getDeployment().getWSDDHandler(qname); } static public WSDDHandler[] getHandlers() { return getWSDDEngineConfiguration().getDeployment().getHandlers(); } static public WSDDService getService(QName qname) { return getWSDDEngineConfiguration().getDeployment().getWSDDService(qname); } static public WSDDService[] getServices() { return getWSDDEngineConfiguration().getDeployment().getServices(); } static public WSDDTransport getTransport(QName qname) { return getWSDDEngineConfiguration().getDeployment().getWSDDTransport(qname); } static public WSDDTransport[] getTransports() { return getWSDDEngineConfiguration().getDeployment().getTransports(); } static public void deployHandler(WSDDHandler handler) { getWSDDEngineConfiguration().getDeployment().deployHandler(handler); } static public void deployService(WSDDService service) { getWSDDEngineConfiguration().getDeployment().deployService(service); } static public void deployTransport(WSDDTransport transport) { getWSDDEngineConfiguration().getDeployment().deployTransport(transport); } static public void undeployHandler(QName qname) { getWSDDEngineConfiguration().getDeployment().undeployHandler(qname); } static public void undeployService(QName qname) { getWSDDEngineConfiguration().getDeployment().undeployService(qname); } static public void undeployTransport(QName qname) { getWSDDEngineConfiguration().getDeployment().undeployTransport(qname); } }
7,824
0
Create_ds/axis-axis1-java/axis-rt-management/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-management/src/main/java/org/apache/axis/management/Registrar.java
/* * Copyright 2003,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.axis.management; import org.apache.axis.components.logger.LogFactory; import org.apache.commons.logging.Log; import org.apache.commons.modeler.Registry; /** * class to act as a dynamic loading registrar to commons-modeler, so * as to autoregister stuff * <p> * <a href="http://www.webweavertech.com/costin/archives/000168.html#000168">http://www.webweavertech.com/costin/archives/000168.html#000168</a> */ public class Registrar { /** * our log */ protected static Log log = LogFactory.getLog(Registrar.class.getName()); /** * register an MBean * * @param objectToRegister * @param name * @param context */ public static boolean register(Object objectToRegister, String name, String context) { if (log.isDebugEnabled()) { log.debug("Registering " + objectToRegister + " as " + name); } try { Registry.getRegistry(null, null).registerComponent(objectToRegister, name, context); return true; } catch (Exception ex) { log.warn(ex); return false; } } }
7,825
0
Create_ds/axis-axis1-java/axis-rt-management/src/main/java/org/apache/axis/management
Create_ds/axis-axis1-java/axis-rt-management/src/main/java/org/apache/axis/management/servlet/AxisServerMBeanExporter.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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.axis.management.servlet; import javax.servlet.ServletContextAttributeEvent; import javax.servlet.ServletContextAttributeListener; import org.apache.axis.management.ServiceAdmin; import org.apache.axis.server.AxisServer; import org.apache.axis.transport.http.AxisServlet; /** * Listener that registers the MBeans for the {@link AxisServer} created by {@link AxisServlet}. To * enable MBean registration in your Web application, add the following configuration to * <tt>web.xml</tt>: * * <pre> * &lt;listener&gt; * &lt;listener-class&gt;org.apache.axis.management.servlet.AxisServerMBeanExporter&lt;/listener-class&gt; * &lt;/listener&gt; * </pre> * * @author Andreas Veithen */ public class AxisServerMBeanExporter implements ServletContextAttributeListener { public void attributeAdded(ServletContextAttributeEvent event) { Object value = event.getValue(); if (value instanceof AxisServer) { ServiceAdmin.setEngine((AxisServer)value, event.getServletContext().getServerInfo()); } } public void attributeRemoved(ServletContextAttributeEvent event) { // TODO: we currently never unregister the MBeans, but this was also the case in Axis 1.4 } public void attributeReplaced(ServletContextAttributeEvent event) { attributeRemoved(event); attributeAdded(event); } }
7,826
0
Create_ds/axis-axis1-java/axis-rt-management/src/main/java/org/apache/axis/management
Create_ds/axis-axis1-java/axis-rt-management/src/main/java/org/apache/axis/management/jmx/WSDDServiceWrapper.java
/* * Copyright 2003,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.axis.management.jmx; import org.apache.axis.deployment.wsdd.WSDDService; public class WSDDServiceWrapper { private WSDDService _wsddService; public WSDDService getWSDDService() { return this._wsddService; } public void setWSDDService(WSDDService wsddService) { this._wsddService = wsddService; } }
7,827
0
Create_ds/axis-axis1-java/axis-rt-management/src/main/java/org/apache/axis/management
Create_ds/axis-axis1-java/axis-rt-management/src/main/java/org/apache/axis/management/jmx/WSDDTransportWrapper.java
/* * Copyright 2003,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.axis.management.jmx; import org.apache.axis.deployment.wsdd.WSDDTransport; public class WSDDTransportWrapper { private WSDDTransport _wsddTransport; public WSDDTransport getWSDDTransport() { return this._wsddTransport; } public void setWSDDTransport(WSDDTransport _wsddTransport) { this._wsddTransport = _wsddTransport; } }
7,828
0
Create_ds/axis-axis1-java/axis-rt-management/src/main/java/org/apache/axis/management
Create_ds/axis-axis1-java/axis-rt-management/src/main/java/org/apache/axis/management/jmx/DeploymentAdministrator.java
/* * Copyright 2003,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.axis.management.jmx; import org.apache.axis.deployment.wsdd.WSDDGlobalConfiguration; import org.apache.axis.deployment.wsdd.WSDDHandler; import org.apache.axis.management.ServiceAdmin; import javax.xml.namespace.QName; public class DeploymentAdministrator implements DeploymentAdministratorMBean { public DeploymentAdministrator() { } public void saveConfiguration() { ServiceAdmin.saveConfiguration(); } public void configureGlobalConfig(WSDDGlobalConfiguration config) { ServiceAdmin.setGlobalConfig(config); } public void deployHandler(WSDDHandler handler) { ServiceAdmin.deployHandler(handler); } public void deployService(WSDDServiceWrapper service) { ServiceAdmin.deployService(service.getWSDDService()); } public void deployTransport(WSDDTransportWrapper transport) { ServiceAdmin.deployTransport(transport.getWSDDTransport()); } public void undeployHandler(String qname) { ServiceAdmin.undeployHandler(new QName(qname)); } public void undeployService(String qname) { ServiceAdmin.undeployService(new QName(qname)); } public void undeployTransport(String qname) { ServiceAdmin.undeployTransport(new QName(qname)); } }
7,829
0
Create_ds/axis-axis1-java/axis-rt-management/src/main/java/org/apache/axis/management
Create_ds/axis-axis1-java/axis-rt-management/src/main/java/org/apache/axis/management/jmx/DeploymentQueryMBean.java
/* * Copyright 2003,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.axis.management.jmx; import org.apache.axis.AxisFault; import org.apache.axis.ConfigurationException; import org.apache.axis.deployment.wsdd.WSDDGlobalConfiguration; import org.apache.axis.deployment.wsdd.WSDDHandler; import org.apache.axis.deployment.wsdd.WSDDService; import org.apache.axis.deployment.wsdd.WSDDTransport; public interface DeploymentQueryMBean { /** * get the global configuration * * @return */ public WSDDGlobalConfiguration findGlobalConfig(); /** * find the handler * * @param qname * @return */ public WSDDHandler findHandler(String qname); /** * return all handlers * * @return */ public WSDDHandler[] findHandlers(); /** * find the service * * @param qname * @return */ public WSDDService findService(String qname); /** * return all services * * @return */ public WSDDService[] findServices(); /** * find the transport * * @param qname * @return */ public WSDDTransport findTransport(String qname); /** * return all transports * * @return */ public WSDDTransport[] findTransports(); /** * List all registered services * * @return string array * @throws org.apache.axis.AxisFault ConfigurationException */ public String[] listServices() throws AxisFault, ConfigurationException; }
7,830
0
Create_ds/axis-axis1-java/axis-rt-management/src/main/java/org/apache/axis/management
Create_ds/axis-axis1-java/axis-rt-management/src/main/java/org/apache/axis/management/jmx/ServiceAdministratorMBean.java
/* * Copyright 2003,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.axis.management.jmx; import org.apache.axis.AxisFault; import org.apache.axis.ConfigurationException; /** * The ServiceAdministrator MBean exposes the * org.apache.axis.management.ServiceAdmin object * * @author bdillon * @version 1.0 */ public interface ServiceAdministratorMBean { /** * get the axis version * * @return */ public String getVersion(); /** * Start the server */ public void start(); /** * stop the server */ public void stop(); /** * restart the server */ public void restart(); /** * Start the Service * * @param serviceName * @throws AxisFault ConfigurationException */ public void startService(String serviceName) throws AxisFault, ConfigurationException; /** * Stop the Service * * @param serviceName * @throws AxisFault ConfigurationException */ public void stopService(String serviceName) throws AxisFault, ConfigurationException; }
7,831
0
Create_ds/axis-axis1-java/axis-rt-management/src/main/java/org/apache/axis/management
Create_ds/axis-axis1-java/axis-rt-management/src/main/java/org/apache/axis/management/jmx/DeploymentQuery.java
/* * Copyright 2003,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.axis.management.jmx; import org.apache.axis.AxisFault; import org.apache.axis.ConfigurationException; import org.apache.axis.deployment.wsdd.WSDDGlobalConfiguration; import org.apache.axis.deployment.wsdd.WSDDHandler; import org.apache.axis.deployment.wsdd.WSDDService; import org.apache.axis.deployment.wsdd.WSDDTransport; import org.apache.axis.management.ServiceAdmin; import javax.xml.namespace.QName; public class DeploymentQuery implements DeploymentQueryMBean { /** * get the global configuration * * @return */ public WSDDGlobalConfiguration findGlobalConfig() { return ServiceAdmin.getGlobalConfig(); } /** * find a specific handler * * @param qname * @return */ public WSDDHandler findHandler(String qname) { return ServiceAdmin.getHandler(new QName(qname)); } /** * get all handlers * * @return */ public WSDDHandler[] findHandlers() { return ServiceAdmin.getHandlers(); } /** * fina a specific service * * @param qname * @return */ public WSDDService findService(String qname) { return ServiceAdmin.getService(new QName(qname)); } /** * get all services * * @return */ public WSDDService[] findServices() { return ServiceAdmin.getServices(); } /** * find a specific transport * * @param qname * @return */ public WSDDTransport findTransport(String qname) { return ServiceAdmin.getTransport(new QName(qname)); } /** * return all transports * * @return */ public WSDDTransport[] findTransports() { return ServiceAdmin.getTransports(); } /** * List all registered services * * @return Map of Services (SOAPService objects, Key is the ServiceName) * @throws AxisFault ConfigurationException */ public String[] listServices() throws AxisFault, ConfigurationException { return org.apache.axis.management.ServiceAdmin.listServices(); } }
7,832
0
Create_ds/axis-axis1-java/axis-rt-management/src/main/java/org/apache/axis/management
Create_ds/axis-axis1-java/axis-rt-management/src/main/java/org/apache/axis/management/jmx/ServiceAdministrator.java
/* * Copyright 2003,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.axis.management.jmx; import org.apache.axis.AxisFault; import org.apache.axis.ConfigurationException; import org.apache.axis.Version; import org.apache.axis.management.ServiceAdmin; /** * The ServiceAdmininstrator MBean exposes the * org.apache.axis.management.ServiceAdmin object * * @author bdillon * @version 1.0 */ public class ServiceAdministrator implements ServiceAdministratorMBean { /** * CTR */ public ServiceAdministrator() { } /** * start the server */ public void start() { ServiceAdmin.start(); } /** * stop the server */ public void stop() { ServiceAdmin.stop(); } /** * restart the server */ public void restart() { ServiceAdmin.restart(); } /** * Start the Service * * @param serviceName * @throws AxisFault ConfigurationException */ public void startService(String serviceName) throws AxisFault, ConfigurationException { org.apache.axis.management.ServiceAdmin.startService(serviceName); } /** * Stop the Service * * @param serviceName * @throws AxisFault ConfigurationException */ public void stopService(String serviceName) throws AxisFault, ConfigurationException { org.apache.axis.management.ServiceAdmin.stopService(serviceName); } /** * get the axis version * * @return */ public String getVersion() { return Version.getVersionText(); } }
7,833
0
Create_ds/axis-axis1-java/axis-rt-management/src/main/java/org/apache/axis/management
Create_ds/axis-axis1-java/axis-rt-management/src/main/java/org/apache/axis/management/jmx/DeploymentAdministratorMBean.java
/* * Copyright 2003,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.axis.management.jmx; import org.apache.axis.deployment.wsdd.WSDDGlobalConfiguration; import org.apache.axis.deployment.wsdd.WSDDHandler; public interface DeploymentAdministratorMBean { public void saveConfiguration(); public void configureGlobalConfig(WSDDGlobalConfiguration config); public void deployHandler(WSDDHandler handler); public void deployService(WSDDServiceWrapper service); public void deployTransport(WSDDTransportWrapper transport); public void undeployHandler(String qname); public void undeployService(String qname); public void undeployTransport(String qname); }
7,834
0
Create_ds/axis-axis1-java/axis-rt-databinding-castor/src/main/java/org/apache/axis/encoding/ser
Create_ds/axis-axis1-java/axis-rt-databinding-castor/src/main/java/org/apache/axis/encoding/ser/castor/CastorEnumTypeSerializerFactory.java
/* * Copyright 2002,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.axis.encoding.ser.castor; import org.apache.axis.encoding.ser.BaseSerializerFactory; import org.apache.axis.encoding.SerializerFactory; import javax.xml.namespace.QName; /** * SerializerFactory for Castor Enum Type objects * * @author Ozzie Gurkan */ public class CastorEnumTypeSerializerFactory extends BaseSerializerFactory { public CastorEnumTypeSerializerFactory(Class javaType, QName xmlType) { super(CastorEnumTypeSerializer.class, xmlType, javaType); } public static SerializerFactory create(Class javaType, QName xmlType) { return new CastorEnumTypeSerializerFactory(javaType, xmlType); } }
7,835
0
Create_ds/axis-axis1-java/axis-rt-databinding-castor/src/main/java/org/apache/axis/encoding/ser
Create_ds/axis-axis1-java/axis-rt-databinding-castor/src/main/java/org/apache/axis/encoding/ser/castor/AxisContentHandler.java
/* * The Apache Software License, Version 1.1 * * * Copyright (c) 2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Axis" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ package org.apache.axis.encoding.ser.castor; import org.apache.axis.encoding.SerializationContext; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; import javax.xml.namespace.QName; import java.io.IOException; /** * This ContentHandler delegates all serialization to an axis SerializationContext * * @author <a href="mailto:fabien.nisol@advalvas.be">Fabien Nisol</a> */ public class AxisContentHandler extends DefaultHandler { /** * serialization context to delegate to */ private SerializationContext context; /** * Creates a contentHandler delegate * * @param context : axis context to delegate to */ public AxisContentHandler(SerializationContext context) { super(); setContext(context); } /** * Getter for property context. * * @return Value of property context. */ public SerializationContext getContext() { return context; } /** * Setter for property context. * * @param context New value of property context. */ public void setContext(SerializationContext context) { this.context = context; } /** * delegates to the serialization context */ public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { try { context.startElement(new QName(uri, localName), attributes); } catch (IOException ioe) { throw new SAXException(ioe); } } /** * delegates to the serialization context */ public void endElement(String uri, String localName, String qName) throws SAXException { try { context.endElement(); } catch (IOException ioe) { throw new SAXException(ioe); } } /** * delegates to the serialization context */ public void characters(char[] ch, int start, int length) throws org.xml.sax.SAXException { try { context.writeChars(ch, start, length); } catch (IOException ioe) { throw new SAXException(ioe); } } }
7,836
0
Create_ds/axis-axis1-java/axis-rt-databinding-castor/src/main/java/org/apache/axis/encoding/ser
Create_ds/axis-axis1-java/axis-rt-databinding-castor/src/main/java/org/apache/axis/encoding/ser/castor/CastorSerializer.java
/* * The Apache Software License, Version 1.1 * * * Copyright (c) 2002 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Axis" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ package org.apache.axis.encoding.ser.castor; import org.apache.axis.Constants; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.encoding.SerializationContext; import org.apache.axis.encoding.Serializer; import org.apache.axis.utils.Messages; import org.apache.axis.wsdl.fromJava.Types; import org.apache.commons.logging.Log; import org.exolab.castor.xml.MarshalException; import org.exolab.castor.xml.Marshaller; import org.exolab.castor.xml.ValidationException; import org.w3c.dom.Element; import org.xml.sax.Attributes; import javax.xml.namespace.QName; import java.io.IOException; /** * Castor serializer * * @author Olivier Brand (olivier.brand@vodafone.com) * @author Steve Loughran * @version 1.0 */ public class CastorSerializer implements Serializer { protected static Log log = LogFactory.getLog(CastorSerializer.class.getName()); /** * Serialize a Castor object. * * @param name * @param attributes * @param value this must be a castor object for marshalling * @param context * @throws IOException for XML schema noncompliance, bad object type, and any IO * trouble. */ public void serialize(QName name, Attributes attributes, Object value, SerializationContext context) throws IOException { try { AxisContentHandler hand = new AxisContentHandler(context); Marshaller marshaller = new Marshaller(hand); // Don't include the DOCTYPE, otherwise an exception occurs due to //2 DOCTYPE defined in the document. The XML fragment is included in //an XML document containing already a DOCTYPE marshaller.setMarshalAsDocument(false); String localPart = name.getLocalPart(); int arrayDims = localPart.indexOf('['); if (arrayDims != -1) { localPart = localPart.substring(0, arrayDims); } marshaller.setRootElement(localPart); // Marshall the Castor object into the stream (sink) marshaller.marshal(value); } catch (MarshalException me) { log.error(Messages.getMessage("castorMarshalException00"), me); throw new IOException(Messages.getMessage( "castorMarshalException00") + me.getLocalizedMessage()); } catch (ValidationException ve) { log.error(Messages.getMessage("castorValidationException00"), ve); throw new IOException(Messages.getMessage( "castorValidationException00") + ve.getLocation() + ": " + ve.getLocalizedMessage()); } } public String getMechanismType() { return Constants.AXIS_SAX; } /** * Return XML schema for the specified type, suitable for insertion into * the &lt;types&gt; element of a WSDL document, or underneath an * &lt;element&gt; or &lt;attribute&gt; declaration. * * @param javaType the Java Class we're writing out schema for * @param types the Java2WSDL Types object which holds the context * for the WSDL being generated. * @return a type element containing a schema simpleType/complexType * @see org.apache.axis.wsdl.fromJava.Types */ public Element writeSchema(Class javaType, Types types) throws Exception { return null; } }
7,837
0
Create_ds/axis-axis1-java/axis-rt-databinding-castor/src/main/java/org/apache/axis/encoding/ser
Create_ds/axis-axis1-java/axis-rt-databinding-castor/src/main/java/org/apache/axis/encoding/ser/castor/CastorEnumTypeDeserializer.java
/* * Copyright 2001,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.axis.encoding.ser.castor; import org.apache.axis.encoding.DeserializationContext; import org.apache.axis.encoding.Deserializer; import org.apache.axis.encoding.DeserializerImpl; import org.apache.axis.message.MessageElement; import org.apache.axis.utils.Messages; import org.xml.sax.SAXException; import javax.xml.namespace.QName; import java.lang.reflect.Method; /** * Castor deserializer * * @author Ozzie Gurkan * @version 1.0 */ public class CastorEnumTypeDeserializer extends DeserializerImpl implements Deserializer { public QName xmlType; public Class javaType; public CastorEnumTypeDeserializer(Class javaType, QName xmlType) { this.xmlType = xmlType; this.javaType = javaType; } public void onEndElement( String namespace, String localName, DeserializationContext context) throws SAXException { try { MessageElement msgElem = context.getCurElement(); if (msgElem != null) { Method method = javaType.getMethod("valueOf", new Class[]{String.class}); value = method.invoke(null, new Object[]{msgElem.getValue()}); } } catch (Exception exp) { log.error(Messages.getMessage("exception00"), exp); throw new SAXException(exp); } } }
7,838
0
Create_ds/axis-axis1-java/axis-rt-databinding-castor/src/main/java/org/apache/axis/encoding/ser
Create_ds/axis-axis1-java/axis-rt-databinding-castor/src/main/java/org/apache/axis/encoding/ser/castor/CastorDeserializer.java
/* * Copyright 2001-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.axis.encoding.ser.castor; import org.apache.axis.encoding.DeserializationContext; import org.apache.axis.encoding.Deserializer; import org.apache.axis.encoding.DeserializerImpl; import org.apache.axis.message.MessageElement; import org.apache.axis.utils.Messages; import org.exolab.castor.xml.MarshalException; import org.exolab.castor.xml.Unmarshaller; import org.exolab.castor.xml.ValidationException; import org.xml.sax.SAXException; import javax.xml.namespace.QName; /** * Castor deserializer * * @author Olivier Brand (olivier.brand@vodafone.com) * @author Steve Loughran * @version 1.0 */ public class CastorDeserializer extends DeserializerImpl implements Deserializer { public QName xmlType; public Class javaType; public CastorDeserializer(Class javaType, QName xmlType) { this.xmlType = xmlType; this.javaType = javaType; } /** * Return something even if no characters were found. */ public void onEndElement( String namespace, String localName, DeserializationContext context) throws SAXException { try { MessageElement msgElem = context.getCurElement(); if (msgElem != null) { // Unmarshall the nested XML element into a castor object of type 'javaType' value = Unmarshaller.unmarshal(javaType, msgElem.getAsDOM()); } } catch (MarshalException me) { log.error(Messages.getMessage("castorMarshalException00"), me); throw new SAXException(Messages.getMessage("castorMarshalException00") + me.getLocalizedMessage()); } catch (ValidationException ve) { log.error(Messages.getMessage("castorValidationException00"), ve); throw new SAXException(Messages.getMessage("castorValidationException00") + ve.getLocation() + ": " + ve.getLocalizedMessage()); } catch (Exception exp) { log.error(Messages.getMessage("exception00"), exp); throw new SAXException(exp); } } }
7,839
0
Create_ds/axis-axis1-java/axis-rt-databinding-castor/src/main/java/org/apache/axis/encoding/ser
Create_ds/axis-axis1-java/axis-rt-databinding-castor/src/main/java/org/apache/axis/encoding/ser/castor/CastorSerializerFactory.java
/* * Copyright 2002-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.axis.encoding.ser.castor; import org.apache.axis.encoding.ser.BaseSerializerFactory; import org.apache.axis.encoding.SerializerFactory; import javax.xml.namespace.QName; /** * SerializerFactory for Castor objects * * @author Olivier Brand (olivier.brand@vodafone.com) */ public class CastorSerializerFactory extends BaseSerializerFactory { public CastorSerializerFactory(Class javaType, QName xmlType) { super(CastorSerializer.class, xmlType, javaType); } public static SerializerFactory create(Class javaType, QName xmlType) { return new CastorSerializerFactory(javaType, xmlType); } }
7,840
0
Create_ds/axis-axis1-java/axis-rt-databinding-castor/src/main/java/org/apache/axis/encoding/ser
Create_ds/axis-axis1-java/axis-rt-databinding-castor/src/main/java/org/apache/axis/encoding/ser/castor/CastorEnumTypeDeserializerFactory.java
/* * Copyright 2002,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.axis.encoding.ser.castor; import org.apache.axis.encoding.ser.BaseDeserializerFactory; import org.apache.axis.encoding.DeserializerFactory; import javax.xml.namespace.QName; /** * A CastorEnumTypeDeserializer Factory * * @author Ozzie Gurkan */ public class CastorEnumTypeDeserializerFactory extends BaseDeserializerFactory { public CastorEnumTypeDeserializerFactory(Class javaType, QName xmlType) { super(CastorEnumTypeDeserializer.class, xmlType, javaType); } public static DeserializerFactory create(Class javaType, QName xmlType) { return new CastorEnumTypeDeserializerFactory(javaType, xmlType); } }
7,841
0
Create_ds/axis-axis1-java/axis-rt-databinding-castor/src/main/java/org/apache/axis/encoding/ser
Create_ds/axis-axis1-java/axis-rt-databinding-castor/src/main/java/org/apache/axis/encoding/ser/castor/CastorDeserializerFactory.java
/* * Copyright 2002-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.axis.encoding.ser.castor; import org.apache.axis.encoding.ser.BaseDeserializerFactory; import org.apache.axis.encoding.DeserializerFactory; import javax.xml.namespace.QName; /** * A CastorDeserializer Factory * * @author Olivier Brand (olivier.brand@vodafone.com) */ public class CastorDeserializerFactory extends BaseDeserializerFactory { public CastorDeserializerFactory(Class javaType, QName xmlType) { super(CastorDeserializer.class, xmlType, javaType); } public static DeserializerFactory create(Class javaType, QName xmlType) { return new CastorDeserializerFactory(javaType, xmlType); } }
7,842
0
Create_ds/axis-axis1-java/axis-rt-databinding-castor/src/main/java/org/apache/axis/encoding/ser
Create_ds/axis-axis1-java/axis-rt-databinding-castor/src/main/java/org/apache/axis/encoding/ser/castor/CastorEnumTypeSerializer.java
/* * Copyright 2002,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.axis.encoding.ser.castor; import org.apache.axis.Constants; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.encoding.SerializationContext; import org.apache.axis.encoding.Serializer; import org.apache.axis.utils.Messages; import org.apache.axis.wsdl.fromJava.Types; import org.apache.commons.logging.Log; import org.w3c.dom.Element; import org.xml.sax.Attributes; import javax.xml.namespace.QName; import java.io.IOException; import java.lang.reflect.Method; import java.util.Enumeration; /** * Castor serializer * * @author Ozzie Gurkan * @version 1.0 */ public class CastorEnumTypeSerializer implements Serializer { protected static Log log = LogFactory.getLog(CastorEnumTypeSerializer.class.getName()); /** * Serialize a Castor Enum Type object. * * @param name * @param attributes * @param value this must be a castor object for marshalling * @param context * @throws IOException for XML schema noncompliance, bad object type, and any IO * trouble. */ public void serialize( QName name, Attributes attributes, Object value, SerializationContext context) throws IOException { context.startElement(name, attributes); try { //get the value of the object Method method = value.getClass().getMethod("toString", new Class[]{}); //call the method to return the string String string = (String) method.invoke(value, new Object[]{}); //write the string context.writeString(string); } catch (Exception me) { log.error(Messages.getMessage("exception00"), me); throw new IOException("Castor object error: " + me.getLocalizedMessage()); } finally { context.endElement(); } } public String getMechanismType() { return Constants.AXIS_SAX; } /** * Return XML schema for the specified type, suitable for insertion into * the &lt;types&gt; element of a WSDL document, or underneath an * &lt;element&gt; or &lt;attribute&gt; declaration. * * @param javaType the Java Class we're writing out schema for * @param types the Java2WSDL Types object which holds the context * for the WSDL being generated. * @return a type element containing a schema simpleType/complexType * @see org.apache.axis.wsdl.fromJava.Types */ public Element writeSchema(Class javaType, Types types) throws Exception { /* <simpleType> <restriction base="xsd:string"> <enumeration value="OK"/> <enumeration value="ERROR"/> <enumeration value="WARNING"/> </restriction> </simpleType> */ Element simpleType = types.createElement("simpleType"); Element restriction = types.createElement("restriction"); simpleType.appendChild(restriction); restriction.setAttribute("base", Constants.NS_PREFIX_SCHEMA_XSD + ":string"); Method enumerateMethod = javaType.getMethod("enumerate", new Class[0]); Enumeration en = (Enumeration) enumerateMethod.invoke(null, new Object[0]); while (en.hasMoreElements()) { Object obj = (Object) en.nextElement(); Method toStringMethod = obj.getClass().getMethod("toString", new Class[0]); String value = (String) toStringMethod.invoke(obj, new Object[0]); Element enumeration = types.createElement("enumeration"); restriction.appendChild(enumeration); enumeration.setAttribute("value", value); } return simpleType; } }
7,843
0
Create_ds/axis-axis1-java/daemon-launcher/src/main/java/org/apache/axis/tools
Create_ds/axis-axis1-java/daemon-launcher/src/main/java/org/apache/axis/tools/daemon/ControlConnectionReader.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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.axis.tools.daemon; import java.io.BufferedReader; import java.io.Reader; import java.util.LinkedList; import org.apache.commons.daemon.Daemon; /** * Reads messages from the control connection. The main purpose of this is to detect as soon as * possible when the control connection is closed by the parent process and to terminate the child * process if that is unexpected. To achieve this we need to read the messages eagerly and place * them into a queue. In particular this covers the case where the child process has received a * <tt>STOP</tt> message and {@link Daemon#stop()} or {@link Daemon#destroy()} hangs. In this case, * if the parent process is terminated (or stops waiting for the <tt>STOPPED</tt> message and closes * the control connection), we can stop the child process immediately. * * @author Andreas Veithen */ final class ControlConnectionReader implements Runnable { private final BufferedReader in; private final LinkedList queue = new LinkedList(); private boolean expectClose; ControlConnectionReader(Reader in) { this.in = new BufferedReader(in); } synchronized String awaitMessage() throws InterruptedException { while (queue.isEmpty()) { wait(); } return (String)queue.removeFirst(); } synchronized void expectClose() { this.expectClose = true; } public void run() { try { String message; while ((message = in.readLine()) != null) { synchronized (this) { queue.add(message); notify(); } } if (!expectClose) { System.err.println("Control connection unexpectedly closed; terminating."); System.exit(1); } } catch (Throwable ex) { ex.printStackTrace(); System.exit(1); } } }
7,844
0
Create_ds/axis-axis1-java/daemon-launcher/src/main/java/org/apache/axis/tools
Create_ds/axis-axis1-java/daemon-launcher/src/main/java/org/apache/axis/tools/daemon/LauncherException.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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.axis.tools.daemon; final class LauncherException extends Exception { private static final long serialVersionUID = 9049901854635661634L; public LauncherException(String msg) { super(msg); } }
7,845
0
Create_ds/axis-axis1-java/daemon-launcher/src/main/java/org/apache/axis/tools
Create_ds/axis-axis1-java/daemon-launcher/src/main/java/org/apache/axis/tools/daemon/Launcher.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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.axis.tools.daemon; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.Writer; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; import org.apache.commons.daemon.Daemon; import org.apache.commons.daemon.DaemonContext; /** * Main class to launch and control a {@link Daemon} implementation. This class is typically * executed in a child JVM and allows the parent process to control the lifecycle of the daemon * instance. The main method takes the following arguments: * <ol> * <li>The class name of the {@link Daemon} implementation. * <li>A TCP port number to use for the control connection. * </ol> * All remaining arguments are passed to the {@link Daemon} implementation. * <p> * The class uses the following protocol to allow the parent process to control the lifecycle of the * daemon: * <ol> * <li>The parent process spawns a new child JVM with this class as main class. It passes the class * name of the {@link Daemon} implementation and the control port as arguments (see above). * <li>The child process opens the specified TCP port and waits for the control connection to be * established. * <li>The parent process connects to the control port. * <li>The child process {@link Daemon#init(DaemonContext) initializes} and {@link Daemon#start() * starts} the daemon. * <li>The child process sends a <tt>READY</tt> message over the control connection to the parent * process. * <li>When the parent process no longer needs the daemon, it sends a <tt>STOP</tt> message to the * child process. * <li>The child process {@link Daemon#stop() stops} and {@link Daemon#destroy() destroys} the * daemon. * <li>The child process sends a <tt>STOPPED</tt> message to the parent process, closes the control * connection and terminates itself. * <li>The parent process closes the control connection. * </ol> * * @author Andreas Veithen */ public class Launcher { public static void main(String[] args) { try { String daemonClass = args[0]; int controlPort = Integer.parseInt(args[1]); String[] daemonArgs = new String[args.length-2]; System.arraycopy(args, 2, daemonArgs, 0, args.length-2); ServerSocket controlServerSocket = new ServerSocket(); controlServerSocket.bind(new InetSocketAddress(InetAddress.getByName("localhost"), controlPort)); Socket controlSocket = controlServerSocket.accept(); // We only accept a single connection; therefore we can close the ServerSocket here controlServerSocket.close(); ControlConnectionReader controlIn = new ControlConnectionReader(new InputStreamReader(controlSocket.getInputStream(), "ASCII")); new Thread(controlIn).start(); Writer controlOut = new OutputStreamWriter(controlSocket.getOutputStream(), "ASCII"); Daemon daemon = (Daemon)Class.forName(daemonClass).newInstance(); daemon.init(new DaemonContextImpl(daemonArgs)); daemon.start(); controlOut.write("READY\r\n"); controlOut.flush(); String request = controlIn.awaitMessage(); if (request.equals("STOP")) { daemon.stop(); daemon.destroy(); controlIn.expectClose(); controlOut.write("STOPPED\r\n"); controlOut.flush(); System.exit(0); } else { throw new LauncherException("Unexpected request: " + request); } } catch (Throwable ex) { ex.printStackTrace(); System.exit(1); } } }
7,846
0
Create_ds/axis-axis1-java/daemon-launcher/src/main/java/org/apache/axis/tools
Create_ds/axis-axis1-java/daemon-launcher/src/main/java/org/apache/axis/tools/daemon/DaemonContextImpl.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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.axis.tools.daemon; import org.apache.commons.daemon.DaemonContext; import org.apache.commons.daemon.DaemonController; final class DaemonContextImpl implements DaemonContext { private final String[] args; public DaemonContextImpl(String[] args) { this.args = args; } public DaemonController getController() { throw new UnsupportedOperationException(); } public String[] getArguments() { return args; } }
7,847
0
Create_ds/axis-axis1-java/axis-rt-jws/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-jws/src/main/java/org/apache/axis/utils/JWSClassLoader.java
/* * Copyright 2002-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.axis.utils; import java.io.ByteArrayOutputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; /** * Class loader for JWS files. There is one of these per JWS class, and * we keep a static Hashtable of them, indexed by class name. When we want * to reload a JWS, we replace the ClassLoader for that class and let the * old one get GC'ed. * * @author Glen Daniels (gdaniels@apache.org) * @author Doug Davis (dug@us.ibm.com) */ public class JWSClassLoader extends ClassLoader { private String classFile = null; private String name = null; /** * Construct a JWSClassLoader with a class name, a parent ClassLoader, * and a filename of a .class file containing the bytecode for the class. * The constructor will load the bytecode, define the class, and register * this JWSClassLoader in the static registry. * * @param name the name of the class which will be created/loaded * @param cl the parent ClassLoader * @param classFile filename of the .class file * @exception FileNotFoundException * @exception IOException */ public JWSClassLoader(String name, ClassLoader cl, String classFile) throws FileNotFoundException, IOException { super(cl); this.name = name + ".class"; this.classFile = classFile; FileInputStream fis = new FileInputStream( classFile ); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte buf[] = new byte[1024]; for(int i = 0; (i = fis.read(buf)) != -1; ) baos.write(buf, 0, i); fis.close(); baos.close(); /* Create a new Class object from it */ /*************************************/ byte[] data = baos.toByteArray(); defineClass( name, data, 0, data.length ); } /** * Overloaded getResourceAsStream() so we can be sure to return the * correct class file regardless of where it might live on our hard * drive. * * @param resourceName the resource to load (should be "classname.class") * @return an InputStream of the class bytes, or null */ public InputStream getResourceAsStream(String resourceName) { try { if (resourceName.equals(name)) return new FileInputStream( classFile ); } catch (FileNotFoundException e) { // Fall through, return null. } return null; } }
7,848
0
Create_ds/axis-axis1-java/axis-rt-jws/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-jws/src/main/java/org/apache/axis/utils/ClasspathUtils.java
/* * ClasspathUtils.java * * Copyright 2001-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.axis.utils; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.FileFilter; import java.net.URL; import java.net.URLClassLoader; import java.net.URLDecoder; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.StringTokenizer; import java.util.jar.Attributes; import java.util.jar.JarFile; import java.util.jar.JarInputStream; import java.util.jar.Manifest; import org.apache.axis.AxisProperties; import org.apache.axis.MessageContext; import org.apache.axis.transport.http.HTTPConstants; /** * Utility class for constructing the classpath */ public class ClasspathUtils { /** * Expand a directory path or list of directory paths (File.pathSeparator * delimited) into a list of file paths of all the jar files in those * directories. * * @param dirPaths The string containing the directory path or list of * directory paths. * @return The file paths of the jar files in the directories. This is an * empty list if no files were found. */ public static List<File> expandDirs(String dirPaths) { StringTokenizer st = new StringTokenizer(dirPaths, File.pathSeparator); List<File> files = new ArrayList<File>(); while (st.hasMoreTokens()) { String d = st.nextToken(); File dir = new File(d); if (dir.isDirectory()) { files.addAll(Arrays.asList(dir.listFiles(new JavaArchiveFilter()))); } } return files; } /** * Check if this inputstream is a jar/zip * @param is * @return true if inputstream is a jar */ public static boolean isJar(InputStream is) { try { JarInputStream jis = new JarInputStream(is); if (jis.getNextEntry() != null) { return true; } } catch (IOException ioe) { } return false; } /** * Get the default classpath from various thingies in the message context * @param msgContext * @return default classpath */ public static List<File> getDefaultClasspath(MessageContext msgContext) { List<File> classpath = new ArrayList<File>(); ClassLoader cl = Thread.currentThread().getContextClassLoader(); fillClassPath(cl, classpath); // Just to be safe (the above doesn't seem to return the webapp // classpath in all cases), manually do this: String webBase = (String) msgContext.getProperty(HTTPConstants.MC_HTTP_SERVLETLOCATION); if (webBase != null) { classpath.add(new File(webBase, "classes")); try { String libBase = webBase + File.separatorChar + "lib"; File libDir = new File(libBase); String[] jarFiles = libDir.list(); for (int i = 0; i < jarFiles.length; i++) { String jarFile = jarFiles[i]; if (jarFile.endsWith(".jar")) { classpath.add(new File(libBase, jarFile)); } } } catch (Exception e) { // Oh well. No big deal. } } // axis.ext.dirs can be used in any appserver getClassPathFromDirectoryProperty(classpath, "axis.ext.dirs"); // classpath used by Jasper getClassPathFromProperty(classpath, "org.apache.catalina.jsp_classpath"); // websphere stuff. getClassPathFromProperty(classpath, "ws.ext.dirs"); getClassPathFromProperty(classpath, "com.ibm.websphere.servlet.application.classpath"); // java class path getClassPathFromProperty(classpath, "java.class.path"); // Load jars from java external directory getClassPathFromDirectoryProperty(classpath, "java.ext.dirs"); // boot classpath isn't found in above search getClassPathFromProperty(classpath, "sun.boot.class.path"); return classpath; } /** * Add all files in the specified directory to the classpath * @param classpath * @param property */ private static void getClassPathFromDirectoryProperty(List<File> classpath, String property) { String dirs = AxisProperties.getProperty(property); try { classpath.addAll(ClasspathUtils.expandDirs(dirs)); } catch (Exception e) { // Oh well. No big deal. } } /** * Add a classpath stored in a property. * @param classpath * @param property */ private static void getClassPathFromProperty(List<File> classpath, String property) { String path = AxisProperties.getProperty(property); if (path != null) { for (String item : path.split(File.pathSeparator)) { classpath.add(new File(item)); } } } /** * Walk the classloader hierarchy and add to the classpath * @param cl * @param classpath */ private static void fillClassPath(ClassLoader cl, List<File> classpath) { while (cl != null) { if (cl instanceof URLClassLoader) { URL[] urls = ((URLClassLoader) cl).getURLs(); for (int i = 0; (urls != null) && i < urls.length; i++) { String path = urls[i].getPath(); //If it is a drive letter, adjust accordingly. if (path.length() >= 3 && path.charAt(0) == '/' && path.charAt(2) == ':') path = path.substring(1); classpath.add(new File(URLDecoder.decode(path))); // if its a jar extract Class-Path entries from manifest File file = new File(urls[i].getFile()); if (file.isFile()) { FileInputStream fis = null; try { fis = new FileInputStream(file); if (isJar(fis)) { JarFile jar = new JarFile(file); Manifest manifest = jar.getManifest(); if (manifest != null) { Attributes attributes = manifest.getMainAttributes(); if (attributes != null) { String s = attributes.getValue(Attributes.Name.CLASS_PATH); String base = file.getParent(); if (s != null) { StringTokenizer st = new StringTokenizer(s, " "); while (st.hasMoreTokens()) { String t = st.nextToken(); classpath.add(new File(base, t)); } } } } } } catch (IOException ioe) { } finally { if (fis != null) { try { fis.close(); } catch (IOException ioe2) { } } } } } } cl = cl.getParent(); } } /** * Filter for zip/jar */ private static class JavaArchiveFilter implements FileFilter { public boolean accept(File file) { String name = file.getName().toLowerCase(); return (name.endsWith(".jar") || name.endsWith(".zip")); } } }
7,849
0
Create_ds/axis-axis1-java/axis-rt-jws/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-jws/src/main/java/org/apache/axis/handlers/JWSHandler.java
/* * Copyright 2001-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.axis.handlers; import org.apache.axis.AxisFault; import org.apache.axis.Constants; import org.apache.axis.MessageContext; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.constants.Scope; import org.apache.axis.handlers.soap.SOAPService; import org.apache.axis.providers.java.RPCProvider; import org.apache.axis.utils.ClasspathUtils; import org.apache.axis.utils.JWSClassLoader; import org.apache.axis.utils.Messages; import org.apache.axis.utils.XMLUtils; import org.apache.commons.logging.Log; import org.w3c.dom.Document; import org.w3c.dom.Element; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.util.Collections; import java.util.HashMap; import java.util.Hashtable; import java.util.Map; import javax.tools.Diagnostic; import javax.tools.Diagnostic.Kind; import javax.tools.DiagnosticCollector; import javax.tools.JavaCompiler; import javax.tools.JavaCompiler.CompilationTask; import javax.tools.JavaFileObject; import javax.tools.StandardJavaFileManager; import javax.tools.StandardLocation; import javax.tools.ToolProvider; /** A <code>JWSHandler</code> sets the target service and JWS filename * in the context depending on the JWS configuration and the target URL. * * @author Glen Daniels (gdaniels@allaire.com) * @author Doug Davis (dug@us.ibm.com) * @author Sam Ruby (rubys@us.ibm.com) */ public class JWSHandler extends BasicHandler { protected static Log log = LogFactory.getLog(JWSHandler.class.getName()); public final String OPTION_JWS_FILE_EXTENSION = "extension"; public final String DEFAULT_JWS_FILE_EXTENSION = Constants.JWS_DEFAULT_FILE_EXTENSION; private final Map/*<String,SOAPService>*/ soapServices = new HashMap(); private final Map/*<String,ClassLoader>*/ classloaders = new Hashtable(); /** * Just set up the service, the inner service will do the rest... */ public void invoke(MessageContext msgContext) throws AxisFault { if (log.isDebugEnabled()) { log.debug("Enter: JWSHandler::invoke"); } try { setupService(msgContext); } catch (Exception e) { log.error( Messages.getMessage("exception00"), e ); throw AxisFault.makeFault(e); } } /** * If our path ends in the right file extension (*.jws), handle all the * work necessary to compile the source file if it needs it, and set * up the "proxy" RPC service surrounding it as the MessageContext's * active service. * */ protected void setupService(MessageContext msgContext) throws Exception { // FORCE the targetService to be JWS if the URL is right. String realpath = msgContext.getStrProp(Constants.MC_REALPATH); String extension = (String)getOption(OPTION_JWS_FILE_EXTENSION); if (extension == null) extension = DEFAULT_JWS_FILE_EXTENSION; if ((realpath!=null) && (realpath.endsWith(extension))) { /* Grab the *.jws filename from the context - should have been */ /* placed there by another handler (ie. HTTPActionHandler) */ /***************************************************************/ String jwsFile = realpath; String rel = msgContext.getStrProp(Constants.MC_RELATIVE_PATH); // Check for file existance, report error with // relative path to avoid giving out directory info. File f2 = new File( jwsFile ); if (!f2.exists()) { throw new FileNotFoundException(rel); } if (rel.charAt(0) == '/') { rel = rel.substring(1); } int lastSlash = rel.lastIndexOf('/'); String dir = null; if (lastSlash > 0) { dir = rel.substring(0, lastSlash); } String file = rel.substring(lastSlash + 1); String outdir = msgContext.getStrProp( Constants.MC_JWS_CLASSDIR ); if ( outdir == null ) outdir = "." ; // Build matching directory structure under the output // directory. In other words, if we have: // /webroot/jws1/Foo.jws // // That will be compiled to: // .../jwsOutputDirectory/jws1/Foo.class if (dir != null) { outdir = outdir + File.separator + dir; } // Confirm output directory exists. If not, create it IF we're // allowed to. // !!! TODO: add a switch to control this. File outDirectory = new File(outdir); if (!outDirectory.exists()) { outDirectory.mkdirs(); } if (log.isDebugEnabled()) log.debug("jwsFile: " + jwsFile ); String jFile = outdir + File.separator + file.substring(0, file.length()-extension.length()+1) + "java" ; String cFile = outdir + File.separator + file.substring(0, file.length()-extension.length()+1) + "class" ; if (log.isDebugEnabled()) { log.debug("jFile: " + jFile ); log.debug("cFile: " + cFile ); log.debug("outdir: " + outdir); } File f1 = new File( cFile ); /* Get the class */ /*****************/ String clsName = null ; //clsName = msgContext.getStrProp(Constants.MC_RELATIVE_PATH); if ( clsName == null ) clsName = f2.getName(); if ( clsName != null && clsName.charAt(0) == '/' ) clsName = clsName.substring(1); clsName = clsName.substring( 0, clsName.length()-extension.length() ); clsName = clsName.replace('/', '.'); if (log.isDebugEnabled()) log.debug("ClsName: " + clsName ); /* Check to see if we need to recompile */ /****************************************/ if ( !f1.exists() || f2.lastModified() > f1.lastModified() ) { /* If the class file doesn't exist, or it's older than the */ /* java file then recompile the java file. */ /* Start by copying the *.jws file to *.java */ /***********************************************************/ log.debug(Messages.getMessage("compiling00", jwsFile) ); log.debug(Messages.getMessage("copy00", jwsFile, jFile) ); FileReader fr = new FileReader( jwsFile ); FileWriter fw = new FileWriter( jFile ); char[] buf = new char[4096]; int rc ; while ( (rc = fr.read( buf, 0, 4095)) >= 0 ) fw.write( buf, 0, rc ); fw.close(); fr.close(); /* Now run javac on the *.java file */ /************************************/ log.debug("javac " + jFile ); // Process proc = rt.exec( "javac " + jFile ); // proc.waitFor(); JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null); fileManager.setLocation(StandardLocation.CLASS_PATH, ClasspathUtils.getDefaultClasspath(msgContext)); fileManager.setLocation(StandardLocation.CLASS_OUTPUT, Collections.singletonList(new File(outdir))); DiagnosticCollector<JavaFileObject> diagnosticCollector = new DiagnosticCollector<JavaFileObject>(); CompilationTask task = compiler.getTask(null, fileManager, diagnosticCollector, null, null, fileManager.getJavaFileObjectsFromFiles(Collections.singletonList(new File(jFile)))); boolean result = task.call(); /* Delete the temporary *.java file and check return code */ /**********************************************************/ (new File(jFile)).delete(); if ( !result ) { /* Delete the *class file - sometimes it gets created even */ /* when there are errors - so erase it so it doesn't */ /* confuse us. */ /***********************************************************/ (new File(cFile)).delete(); Document doc = XMLUtils.newDocument(); Element root = doc.createElementNS("", "Errors"); StringBuffer message = new StringBuffer("Error compiling "); message.append(jFile); message.append(":"); for (Diagnostic<? extends JavaFileObject> diagnostic : diagnosticCollector.getDiagnostics()) { if (diagnostic.getKind() == Kind.ERROR) { message.append("\nLine "); message.append(diagnostic.getLineNumber()); message.append(", column "); message.append(diagnostic.getStartPosition()); message.append(": "); message.append(diagnostic.getMessage(null)); } } root.appendChild( doc.createTextNode( message.toString() ) ); throw new AxisFault( "Server.compileError", Messages.getMessage("badCompile00", jFile), null, new Element[] { root } ); } classloaders.remove( clsName ); // And clean out the cached service. soapServices.remove(clsName); } ClassLoader cl = (ClassLoader)classloaders.get(clsName); if (cl == null) { cl = new JWSClassLoader(clsName, msgContext.getClassLoader(), cFile); classloaders.put(clsName, cl); } msgContext.setClassLoader(cl); /* Create a new RPCProvider - this will be the "service" */ /* that we invoke. */ /******************************************************************/ // Cache the rpc service created to handle the class. The cache // is based on class name, so only one .jws/.jwr class can be active // in the system at a time. SOAPService rpc = (SOAPService)soapServices.get(clsName); if (rpc == null) { rpc = new SOAPService(new RPCProvider()); rpc.setName(clsName); rpc.setOption(RPCProvider.OPTION_CLASSNAME, clsName ); rpc.setEngine(msgContext.getAxisEngine()); // Support specification of "allowedMethods" as a parameter. String allowed = (String)getOption(RPCProvider.OPTION_ALLOWEDMETHODS); if (allowed == null) allowed = "*"; rpc.setOption(RPCProvider.OPTION_ALLOWEDMETHODS, allowed); // Take the setting for the scope option from the handler // parameter named "scope" String scope = (String)getOption(RPCProvider.OPTION_SCOPE); if (scope == null) scope = Scope.DEFAULT.getName(); rpc.setOption(RPCProvider.OPTION_SCOPE, scope); rpc.getInitializedServiceDesc(msgContext); soapServices.put(clsName, rpc); } // Set engine, which hooks up type mappings. rpc.setEngine(msgContext.getAxisEngine()); rpc.init(); // ?? // OK, this is now the destination service! msgContext.setService( rpc ); } if (log.isDebugEnabled()) { log.debug("Exit: JWSHandler::invoke"); } } public void generateWSDL(MessageContext msgContext) throws AxisFault { try { setupService(msgContext); } catch (Exception e) { log.error( Messages.getMessage("exception00"), e ); throw AxisFault.makeFault(e); } } }
7,850
0
Create_ds/frigga/src/main/java/com/netflix
Create_ds/frigga/src/main/java/com/netflix/frigga/NameValidation.java
/** * Copyright 2012 Netflix, Inc. * * 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 com.netflix.frigga; import java.util.regex.Pattern; /** * Contains static validation methods for checking if a name conforms to Asgard naming standards. */ public class NameValidation { private static final Pattern NAME_HYPHEN_CHARS_PATTERN = Pattern.compile("^[" + NameConstants.NAME_HYPHEN_CHARS + "]+"); private static final Pattern NAME_CHARS_PATTERN = Pattern.compile("^[" + NameConstants.NAME_CHARS + "]+"); private static final Pattern PUSH_FORMAT_PATTERN = Pattern.compile(".*?" + NameConstants.PUSH_FORMAT); private static final Pattern LABELED_VARIABLE_PATTERN = Pattern.compile("^(.*?-)?" + NameConstants.LABELED_VARIABLE + ".*?$"); private NameValidation() { } /** * Validates if provided value is non-null and non-empty. * * @param value the string to validate * @param variableName name of the variable to include in error messages * @return the value parameter if valid, throws an exception otherwise */ public static String notEmpty(String value, String variableName) { if (value == null) { throw new NullPointerException("ERROR: Trying to use String with null " + variableName); } if (value.isEmpty()) { throw new IllegalArgumentException("ERROR: Illegal empty string for " + variableName); } return value; } /** * Validates a name of a cloud object. The name can contain letters, numbers, dots, and underscores. * * @param name the string to validate * @return true if the name is valid */ public static boolean checkName(String name) { return checkMatch(name, NAME_CHARS_PATTERN); } /** * Validates a name of a cloud object. The name can contain hyphens in addition to letters, numbers, dots, and * underscores. * * @param name the string to validate * @return true if the name is valid */ public static boolean checkNameWithHyphen(String name) { return checkMatch(name, NAME_HYPHEN_CHARS_PATTERN); } /** * The detail part of an auto scaling group name can include letters, numbers, dots, underscores, and hyphens. * Restricting the ASG name this way allows safer assumptions in other code about ASG names, like a promise of no * spaces, hash marks, percent signs, or dollar signs. * * @deprecated use checkNameWithHyphen * @param detail the detail string to validate * @return true if the detail is valid */ @Deprecated public static boolean checkDetail(String detail) { return checkMatch(detail, NAME_HYPHEN_CHARS_PATTERN); } /** * Determines whether a name ends with the reserved format -v000 where 0 represents any digit, or starts with the * reserved format z0 where z is any letter, or contains a hyphen-separated token that starts with the z0 format. * * @param name to inspect * @return true if the name ends with the reserved format */ public static Boolean usesReservedFormat(String name) { return checkMatch(name, PUSH_FORMAT_PATTERN) || checkMatch(name, LABELED_VARIABLE_PATTERN); } private static boolean checkMatch(String input, Pattern pattern) { return input != null && pattern.matcher(input).matches(); } }
7,851
0
Create_ds/frigga/src/main/java/com/netflix
Create_ds/frigga/src/main/java/com/netflix/frigga/NameConstants.java
/** * Copyright 2012 Netflix, Inc. * * 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 com.netflix.frigga; /** * Constants used in name parsing, name construction, and name validation. */ public interface NameConstants { String NAME_CHARS = "a-zA-Z0-9._"; String EXTENDED_NAME_CHARS = NAME_CHARS + "~\\^"; String NAME_HYPHEN_CHARS = "-" + EXTENDED_NAME_CHARS; String PUSH_FORMAT = "v([0-9]{3,6})"; String COUNTRIES_KEY = "c"; String DEV_PHASE_KEY = "d"; String HARDWARE_KEY = "h"; String PARTNERS_KEY = "p"; String REVISION_KEY = "r"; String USED_BY_KEY = "u"; String RED_BLACK_SWAP_KEY = "w"; String ZONE_KEY = "z"; String EXISTING_LABELS = "[" + COUNTRIES_KEY + DEV_PHASE_KEY + HARDWARE_KEY + PARTNERS_KEY + REVISION_KEY + USED_BY_KEY + RED_BLACK_SWAP_KEY + ZONE_KEY + "]"; String LABELED_VAR_SEPARATOR = "0"; String LABELED_VAR_VALUES = "[a-zA-Z0-9]"; String LABELED_VARIABLE = EXISTING_LABELS + "[" + LABELED_VAR_SEPARATOR + "]" + LABELED_VAR_VALUES + "+"; }
7,852
0
Create_ds/frigga/src/main/java/com/netflix
Create_ds/frigga/src/main/java/com/netflix/frigga/NameBuilder.java
/** * Copyright 2012 Netflix, Inc. * * 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 com.netflix.frigga; /** * Abstract class for classes in charge of constructing Asgard names. */ public abstract class NameBuilder { protected String combineAppStackDetail(String appName, String stack, String detail) { NameValidation.notEmpty(appName, "appName"); // Use empty strings, not null references that output "null" stack = stack != null ? stack : ""; if (detail != null && !detail.isEmpty()) { return appName + "-" + stack + "-" + detail; } if (!stack.isEmpty()) { return appName + "-" + stack; } return appName; } }
7,853
0
Create_ds/frigga/src/main/java/com/netflix
Create_ds/frigga/src/main/java/com/netflix/frigga/Names.java
/** * Copyright 2012 Netflix, Inc. * * 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 com.netflix.frigga; import com.netflix.frigga.conventions.labeledvariables.LabeledVariables; import com.netflix.frigga.conventions.labeledvariables.LabeledVariablesNamingConvention; import com.netflix.frigga.conventions.labeledvariables.LabeledVariablesNamingResult; import com.netflix.frigga.extensions.NamingConvention; import java.util.Objects; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Function; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Class that can deconstruct information about AWS Auto Scaling Groups, Load Balancers, Launch Configurations, and * Security Groups created by Asgard based on their name. */ public class Names { private static final Pattern PUSH_PATTERN = Pattern.compile( "^([" + NameConstants.NAME_HYPHEN_CHARS + "]*)-(" + NameConstants.PUSH_FORMAT + ")$"); private static final Pattern NAME_PATTERN = Pattern.compile( "^([" + NameConstants.NAME_CHARS + "]+)(?:-([" + NameConstants.NAME_CHARS + "]*)(?:-([" + NameConstants.NAME_HYPHEN_CHARS + "]*?))?)?$"); private static final LabeledVariablesNamingConvention LABELED_VARIABLES_CONVENTION = new LabeledVariablesNamingConvention(); private final String group; private final String cluster; private final String app; private final String stack; private final String detail; private final String push; private final Integer sequence; private final AtomicReference<LabeledVariablesNamingResult> labeledVariables = new AtomicReference<>(); protected Names(String name) { String group = null; String cluster = null; String app = null; String stack = null; String detail = null; String push = null; Integer sequence = null; if (name != null && !name.trim().isEmpty()) { Matcher pushMatcher = PUSH_PATTERN.matcher(name); boolean hasPush = pushMatcher.matches(); String theCluster = hasPush ? pushMatcher.group(1) : name; Matcher nameMatcher = NAME_PATTERN.matcher(theCluster); if (nameMatcher.matches()) { group = name; cluster = theCluster; push = hasPush ? pushMatcher.group(2) : null; String sequenceString = hasPush ? pushMatcher.group(3) : null; if (sequenceString != null) { sequence = Integer.parseInt(sequenceString); } app = nameMatcher.group(1); stack = checkEmpty(nameMatcher.group(2)); detail = checkEmpty(nameMatcher.group(3)); } } this.group = group; this.cluster = cluster; this.app = app; this.stack = stack; this.detail = detail; this.push = push; this.sequence = sequence; } /** * Breaks down the name of an auto scaling group, security group, or load balancer created by Asgard into its * component parts. * * @param name the name of an auto scaling group, security group, or load balancer * @return bean containing the component parts of the compound name */ public static Names parseName(String name) { return new Names(name); } private String checkEmpty(String input) { return (input != null && !input.isEmpty()) ? input : null; } public String getGroup() { return group; } public String getCluster() { return cluster; } public String getApp() { return app; } public String getStack() { return stack; } public String getDetail() { return detail; } public String getPush() { return push; } public Integer getSequence() { return sequence; } public String getCountries() { return getLabeledVariable(LabeledVariables::getCountries); } public String getDevPhase() { return getLabeledVariable(LabeledVariables::getDevPhase); } public String getHardware() { return getLabeledVariable(LabeledVariables::getHardware); } public String getPartners() { return getLabeledVariable(LabeledVariables::getPartners); } public String getRevision() { return getLabeledVariable(LabeledVariables::getRevision); } public String getUsedBy() { return getLabeledVariable(LabeledVariables::getUsedBy); } public String getRedBlackSwap() { return getLabeledVariable(LabeledVariables::getRedBlackSwap); } public String getZone() { return getLabeledVariable(LabeledVariables::getZone); } private <T> T getLabeledVariable(Function<LabeledVariables, T> extractor) { LabeledVariablesNamingResult result = labeledVariables.get(); if (result == null) { LabeledVariablesNamingResult applied = LABELED_VARIABLES_CONVENTION.extractNamingConvention(cluster); if (labeledVariables.compareAndSet(null, applied)) { result = applied; } else { result = labeledVariables.get(); } } return result.getResult().map(extractor).orElse(null); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Names names = (Names) o; return Objects.equals(group, names.group); } @Override public int hashCode() { return Objects.hash(group); } @Override public String toString() { return "Names{" + "group='" + group + '\'' + ", cluster='" + cluster + '\'' + ", app='" + app + '\'' + ", stack='" + stack + '\'' + ", detail='" + detail + '\'' + ", push='" + push + '\'' + ", sequence=" + sequence + '}'; } }
7,854
0
Create_ds/frigga/src/main/java/com/netflix/frigga
Create_ds/frigga/src/main/java/com/netflix/frigga/ami/AppVersion.java
/** * Copyright 2012 Netflix, Inc. * * 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 com.netflix.frigga.ami; import com.netflix.frigga.NameConstants; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Java bean containing the various pieces of information contained in the appversion tag of an AMI formatted with * Netflix standards. Construct using the {@link parseName} factory method. */ public class AppVersion implements Comparable<AppVersion> { /** * Valid app patterns. For example, all of these are valid: * subscriberha-1.0.0-586499 * subscriberha-1.0.0-586499.h150 * subscriberha-1.0.0-586499.h150/WE-WAPP-subscriberha/150 */ private static final Pattern APP_VERSION_PATTERN = Pattern.compile( "([" + NameConstants.NAME_HYPHEN_CHARS + "]+)-([0-9.a-zA-Z~]+)-(\\w+)(?:[.](\\w+))?(?:~[" + NameConstants.NAME_HYPHEN_CHARS + "]+)?(?:\\/([" + NameConstants.NAME_HYPHEN_CHARS + "]+)\\/([0-9]+))?"); private String packageName; private String version; private String buildJobName; private String buildNumber; private String commit; private AppVersion() { } /** * Parses the appversion tag into its component parts. * * @param amiName the text of the AMI's appversion tag * @return bean representing the component parts of the appversion tag */ public static AppVersion parseName(String amiName) { if (amiName == null) { return null; } Matcher matcher = APP_VERSION_PATTERN.matcher(amiName); if (!matcher.matches()) { return null; } AppVersion parsedName = new AppVersion(); parsedName.packageName = matcher.group(1); parsedName.version = matcher.group(2); // Historically we put the change number first because with Perforce it was a number we could use to sort. // This broke when we started using git, since hashes have no order. For a while the stash builds ommited the // commit id, but eventually we began appending it after the build number. boolean buildFirst = matcher.group(3) != null && matcher.group(3).startsWith("h"); // 'h' is for Hudson String buildString = matcher.group(buildFirst ? 3 : 4); parsedName.buildNumber = buildString != null ? buildString.substring(1) : null; parsedName.commit = matcher.group(buildFirst ? 4 : 3); parsedName.buildJobName = matcher.group(5); return parsedName; } @Override public int compareTo(AppVersion other) { if (this == other) { // if x.equals(y), then x.compareTo(y) should be 0 return 0; } if (other == null) { return 1; // equals(null) can never be true, so compareTo(null) should never be 0 } int comparison = nullSafeStringComparator(packageName, other.packageName); if (comparison != 0) { return comparison; } comparison = nullSafeStringComparator(version, other.version); if (comparison != 0) { return comparison; } comparison = nullSafeStringComparator(buildJobName, other.buildJobName); if (comparison != 0) { return comparison; } comparison = nullSafeStringComparator(buildNumber, other.buildNumber); if (comparison != 0) { return comparison; } comparison = nullSafeStringComparator(commit, other.commit); return comparison; } private int nullSafeStringComparator(final String one, final String two) { if (one == null && two == null) { return 0; } if (one == null || two == null) { return (one == null) ? -1 : 1; } return one.compareTo(two); } /** * The regex used for deconstructing the appversion string. */ public static Pattern getAppVersionPattern() { return APP_VERSION_PATTERN; } /** * The name of the RPM package used to create this AMI. */ public String getPackageName() { return packageName; } /** * The version of the RPM package used to create this AMI. */ public String getVersion() { return version; } /** * The Jenkins job that generated the binary deployed on this AMI. */ public String getBuildJobName() { return buildJobName; } /** * The Jenkins build number that generated the binary on this AMI. */ public String getBuildNumber() { return buildNumber; } /** * Identifier of the commit used in the Jenkins builds. Works with both Perforce CLs or git hashes. * @since 0.4 */ public String getCommit() { return commit; } /** * @deprecated As of version 0.4, replaced by {@link getCommit()} */ @Deprecated public String getChangelist() { return commit; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("AppVersion [packageName=").append(packageName).append(", version=").append(version) .append(", buildJobName=").append(buildJobName).append(", buildNumber=").append(buildNumber) .append(", changelist=").append(commit).append("]"); return builder.toString(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((buildJobName == null) ? 0 : buildJobName.hashCode()); result = prime * result + ((buildNumber == null) ? 0 : buildNumber.hashCode()); result = prime * result + ((commit == null) ? 0 : commit.hashCode()); result = prime * result + ((packageName == null) ? 0 : packageName.hashCode()); result = prime * result + ((version == null) ? 0 : version.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; AppVersion other = (AppVersion) obj; if (buildJobName == null) { if (other.buildJobName != null) return false; } else if (!buildJobName.equals(other.buildJobName)) return false; if (buildNumber == null) { if (other.buildNumber != null) return false; } else if (!buildNumber.equals(other.buildNumber)) return false; if (commit == null) { if (other.commit != null) return false; } else if (!commit.equals(other.commit)) return false; if (packageName == null) { if (other.packageName != null) return false; } else if (!packageName.equals(other.packageName)) return false; if (version == null) { if (other.version != null) return false; } else if (!version.equals(other.version)) return false; return true; } }
7,855
0
Create_ds/frigga/src/main/java/com/netflix/frigga
Create_ds/frigga/src/main/java/com/netflix/frigga/ami/BaseAmiInfo.java
/** * Copyright 2012 Netflix, Inc. * * 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 com.netflix.frigga.ami; import java.text.SimpleDateFormat; import java.util.Date; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Bean containing the various pieces of information available from the description of an AMI created by Netflix's * bakery. Construct using the {@link parseDescription} factory method. */ public class BaseAmiInfo { private static final String IMAGE_ID = "ami-[a-z0-9]{8}"; private static final Pattern BASE_AMI_ID_PATTERN = Pattern.compile("^.*?base_ami_id=(" + IMAGE_ID + ").*?"); private static final Pattern ANCESTOR_ID_PATTERN = Pattern.compile("^.*?ancestor_id=(" + IMAGE_ID + ").*?$"); private static final Pattern BASE_AMI_NAME_PATTERN = Pattern.compile("^.*?base_ami_name=([^,]+).*?$"); private static final Pattern ANCESTOR_NAME_PATTERN = Pattern.compile("^.*?ancestor_name=([^,]+).*?$"); private static final Pattern AMI_DATE_PATTERN = Pattern.compile(".*\\-(20[0-9]{6})(\\-.*)?"); private String baseAmiId; private String baseAmiName; private Date baseAmiDate; private BaseAmiInfo() { } /** * Parse an AMI description into its component parts. * * @param imageDescription description field of an AMI created by Netflix's bakery * @return bean representing the component parts of the AMI description */ public static BaseAmiInfo parseDescription(String imageDescription) { BaseAmiInfo info = new BaseAmiInfo(); if (imageDescription == null) { return info; } info.baseAmiId = extractBaseAmiId(imageDescription); info.baseAmiName = extractBaseAmiName(imageDescription); if (info.baseAmiName != null) { Matcher dateMatcher = AMI_DATE_PATTERN.matcher(info.baseAmiName); if (dateMatcher.matches()) { try { // Example: 20100823 info.baseAmiDate = new SimpleDateFormat("yyyyMMdd").parse(dateMatcher.group(1)); } catch (Exception ignored) { // Ignore failure. } } } return info; } private static String extractBaseAmiId(String imageDescription) { // base_ami_id=ami-1eb75c77,base_ami_name=servicenet-roku-qadd.dc.81210.10.44 Matcher matcher = BASE_AMI_ID_PATTERN.matcher(imageDescription); if (matcher.matches()) { return matcher.group(1); } // store=ebs,ancestor_name=ebs-centosbase-x86_64-20101124,ancestor_id=ami-7b4eb912 matcher = ANCESTOR_ID_PATTERN.matcher(imageDescription); if (matcher.matches()) { return matcher.group(1); } return null; } private static String extractBaseAmiName(String imageDescription) { // base_ami_id=ami-1eb75c77,base_ami_name=servicenet-roku-qadd.dc.81210.10.44 Matcher matcher = BASE_AMI_NAME_PATTERN.matcher(imageDescription); if (matcher.matches()) { return matcher.group(1); } // store=ebs,ancestor_name=ebs-centosbase-x86_64-20101124,ancestor_id=ami-7b4eb912 matcher = ANCESTOR_NAME_PATTERN.matcher(imageDescription); if (matcher.matches()) { return matcher.group(1); } return null; } public String getBaseAmiId() { return baseAmiId; } public String getBaseAmiName() { return baseAmiName; } public Date getBaseAmiDate() { return baseAmiDate != null ? (Date) baseAmiDate.clone() : null; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((baseAmiDate == null) ? 0 : baseAmiDate.hashCode()); result = prime * result + ((baseAmiId == null) ? 0 : baseAmiId.hashCode()); result = prime * result + ((baseAmiName == null) ? 0 : baseAmiName.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; BaseAmiInfo other = (BaseAmiInfo) obj; if (baseAmiDate == null) { if (other.baseAmiDate != null) return false; } else if (!baseAmiDate.equals(other.baseAmiDate)) return false; if (baseAmiId == null) { if (other.baseAmiId != null) return false; } else if (!baseAmiId.equals(other.baseAmiId)) return false; if (baseAmiName == null) { if (other.baseAmiName != null) return false; } else if (!baseAmiName.equals(other.baseAmiName)) return false; return true; } @Override public String toString() { return "BaseAmiInfo [baseAmiId=" + baseAmiId + ", baseAmiName=" + baseAmiName + ", baseAmiDate=" + baseAmiDate + "]"; } }
7,856
0
Create_ds/frigga/src/main/java/com/netflix/frigga
Create_ds/frigga/src/main/java/com/netflix/frigga/cluster/ClusterGrouper.java
/** * Copyright 2012 Netflix, Inc. * * 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 com.netflix.frigga.cluster; import com.netflix.frigga.Names; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Utility methods for grouping ASG related objects by cluster. The cluster name is derived from the name of the ASG. */ public class ClusterGrouper { private ClusterGrouper() { } /** * Groups a list of ASG related objects by cluster name. * * @param <T> Type to group * @param inputs list of objects associated with an ASG * @param nameProvider strategy object used to extract the ASG name of the object type of the input list * @return map of cluster name to list of input object */ public static <T> Map<String, List<T>> groupByClusterName(List<T> inputs, AsgNameProvider<T> nameProvider) { Map<String, List<T>> clusterNamesToAsgs = new HashMap<String, List<T>>(); for (T input : inputs) { String clusterName = Names.parseName(nameProvider.extractAsgName(input)).getCluster(); if (!clusterNamesToAsgs.containsKey(clusterName)) { clusterNamesToAsgs.put(clusterName, new ArrayList<T>()); } clusterNamesToAsgs.get(clusterName).add(input); } return clusterNamesToAsgs; } /** * Groups a list of ASG names by cluster name. * * @param asgNames list of asg names * @return map of cluster name to list of ASG names in that cluster */ public static Map<String, List<String>> groupAsgNamesByClusterName(List<String> asgNames) { return groupByClusterName(asgNames, new AsgNameProvider<String>() { public String extractAsgName(String asgName) { return asgName; } }); } }
7,857
0
Create_ds/frigga/src/main/java/com/netflix/frigga
Create_ds/frigga/src/main/java/com/netflix/frigga/cluster/AsgNameProvider.java
/** * Copyright 2012 Netflix, Inc. * * 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 com.netflix.frigga.cluster; /** * Command object for extracting the ASG name from the provided type. Used with grouping ASGs by cluster. * * @param <T> Type to extract ASG name from */ public interface AsgNameProvider<T> { /** * Extracts the ASG name from an input object. * * @param object the object to inspect * @return asg name of the provided object */ String extractAsgName(T object); }
7,858
0
Create_ds/frigga/src/main/java/com/netflix/frigga
Create_ds/frigga/src/main/java/com/netflix/frigga/elb/LoadBalancerNameBuilder.java
/** * Copyright 2012 Netflix, Inc. * * 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 com.netflix.frigga.elb; import com.netflix.frigga.NameBuilder; /** * Logic for constructing the name of a new load balancer in Asgard. */ public class LoadBalancerNameBuilder extends NameBuilder { private String appName; private String stack; private String detail; /** * Constructs and returns the name of the load balancer. * * @return load balancer name */ public String buildLoadBalancerName() { return combineAppStackDetail(appName, stack, detail); } public String getAppName() { return appName; } public void setAppName(String appName) { this.appName = appName; } public String getStack() { return stack; } public void setStack(String stack) { this.stack = stack; } public String getDetail() { return detail; } public void setDetail(String detail) { this.detail = detail; } }
7,859
0
Create_ds/frigga/src/main/java/com/netflix/frigga
Create_ds/frigga/src/main/java/com/netflix/frigga/extensions/NamingResult.java
/** * Copyright 2020 Netflix, Inc. * * 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 com.netflix.frigga.extensions; import java.util.Collection; import java.util.Collections; import java.util.Optional; /** * The result of applying a NamingConvention. * * @param <T> the type of the result extracted from the name */ public interface NamingResult<T> { /** * @return the result (if any) extracted by a NamingConvention */ Optional<T> getResult(); /** * @return the remaining part of a name component after applying a NamingConvention */ String getUnprocessed(); /** * Warnings encountered applying a NamingConvention. * * Warnings are non fatal. * * @return any warnings encountered applying a NamingConvention. */ default Collection<String> getWarnings() { return Collections.emptyList(); } /** * Errors encountered applying a NamingConvention. * * Errors are fatal - if errors were encountered this NamingResult should be considered unusable. * * @return any errors encountered applying a NamingConvention */ default Collection<String> getErrors() { return Collections.emptyList(); } /** * @return whether this NamingResult represents a valid application of a NamingConvention */ default boolean isValid() { return getErrors().isEmpty(); } }
7,860
0
Create_ds/frigga/src/main/java/com/netflix/frigga
Create_ds/frigga/src/main/java/com/netflix/frigga/extensions/NamingConvention.java
/** * Copyright 2020 Netflix, Inc. * * 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 com.netflix.frigga.extensions; /** * A NamingConvention can examine a component of a name to extract encoded values. * * @param <R> the NamingResult type */ public interface NamingConvention<R extends NamingResult<?>> { /** * Parses the nameComponent to extract the naming convention into a typed object * @param nameComponent the name component to examine * @return The NamingResult, never null */ R extractNamingConvention(String nameComponent); }
7,861
0
Create_ds/frigga/src/main/java/com/netflix/frigga/conventions
Create_ds/frigga/src/main/java/com/netflix/frigga/conventions/labeledvariables/LabeledVariablesNamingConvention.java
/** * Copyright 2020 Netflix, Inc. * * 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 com.netflix.frigga.conventions.labeledvariables; import com.netflix.frigga.NameConstants; import com.netflix.frigga.extensions.NamingConvention; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * A NamingConvention that applies the legacy labeled variables convention against a name. * * This logic was extracted out of Names (and referenced from there for backwards-ish compatibility). */ public class LabeledVariablesNamingConvention implements NamingConvention<LabeledVariablesNamingResult> { private static final Pattern LABELED_VARS_PATTERN = Pattern.compile( "(.*?)((?:(?:^|-)" +NameConstants.LABELED_VARIABLE + ")+)$"); //-------------------------- //VisibleForTesting: static final Pattern LABELED_COUNTRIES_PATTERN = createLabeledVariablePattern(NameConstants.COUNTRIES_KEY); static final Pattern LABELED_DEV_PHASE_KEY_PATTERN = createLabeledVariablePattern(NameConstants.DEV_PHASE_KEY); static final Pattern LABELED_HARDWARE_KEY_PATTERN = createLabeledVariablePattern(NameConstants.HARDWARE_KEY); static final Pattern LABELED_PARTNERS_KEY_PATTERN = createLabeledVariablePattern(NameConstants.PARTNERS_KEY); static final Pattern LABELED_REVISION_KEY_PATTERN = createLabeledVariablePattern(NameConstants.REVISION_KEY); static final Pattern LABELED_USED_BY_KEY_PATTERN = createLabeledVariablePattern(NameConstants.USED_BY_KEY); static final Pattern LABELED_RED_BLACK_SWAP_KEY_PATTERN = createLabeledVariablePattern(NameConstants.RED_BLACK_SWAP_KEY); static final Pattern LABELED_ZONE_KEY_PATTERN = createLabeledVariablePattern(NameConstants.ZONE_KEY); //-------------------------- @Override public LabeledVariablesNamingResult extractNamingConvention(String nameComponent) { if (nameComponent == null || nameComponent.isEmpty()) { return LabeledVariablesNamingResult.EMPTY; } Matcher labeledVarsMatcher = LABELED_VARS_PATTERN.matcher(nameComponent); boolean labeledAndUnlabeledMatches = labeledVarsMatcher.matches(); if (!labeledAndUnlabeledMatches) { return LabeledVariablesNamingResult.EMPTY; } String unprocessed = labeledVarsMatcher.group(1); String labeledVariables = labeledVarsMatcher.group(2); String countries = extractLabeledVariable(labeledVariables, LABELED_COUNTRIES_PATTERN); String devPhase = extractLabeledVariable(labeledVariables, LABELED_DEV_PHASE_KEY_PATTERN); String hardware = extractLabeledVariable(labeledVariables, LABELED_HARDWARE_KEY_PATTERN); String partners = extractLabeledVariable(labeledVariables, LABELED_PARTNERS_KEY_PATTERN); String revision = extractLabeledVariable(labeledVariables, LABELED_REVISION_KEY_PATTERN); String usedBy = extractLabeledVariable(labeledVariables, LABELED_USED_BY_KEY_PATTERN); String redBlackSwap = extractLabeledVariable(labeledVariables, LABELED_RED_BLACK_SWAP_KEY_PATTERN); String zone = extractLabeledVariable(labeledVariables, LABELED_ZONE_KEY_PATTERN); return new LabeledVariablesNamingResult(new LabeledVariables(countries, devPhase, hardware, partners, revision, usedBy, redBlackSwap, zone), unprocessed); } //VisibleForTesting static String extractLabeledVariable(String labeledVariablesString, Pattern labelPattern) { if (labeledVariablesString != null && !labeledVariablesString.isEmpty()) { Matcher labelMatcher = labelPattern.matcher(labeledVariablesString); boolean hasLabel = labelMatcher.find(); if (hasLabel) { return labelMatcher.group(1); } } return null; } private static Pattern createLabeledVariablePattern(String label) { if (label == null || label.length() != 1 || !NameConstants.EXISTING_LABELS.contains(label)) { throw new IllegalArgumentException(String.format("Invalid label %s must be one of %s", label, NameConstants.EXISTING_LABELS)); } String labeledVariablePattern = "-?" + label + NameConstants.LABELED_VAR_SEPARATOR + "(" + NameConstants.LABELED_VAR_VALUES + "+)"; return Pattern.compile(labeledVariablePattern); } }
7,862
0
Create_ds/frigga/src/main/java/com/netflix/frigga/conventions
Create_ds/frigga/src/main/java/com/netflix/frigga/conventions/labeledvariables/LabeledVariablesNamingResult.java
/** * Copyright 2020 Netflix, Inc. * * 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 com.netflix.frigga.conventions.labeledvariables; import com.netflix.frigga.extensions.NamingResult; import java.util.Optional; /** * The result of applying the LabeledVariablesNamingConvention. * * Contains LabeledVariables for the extracted labeled variables, as well as * the unprocessed leading component of the name up to the start of the first labeled * variable. */ public class LabeledVariablesNamingResult implements NamingResult<LabeledVariables> { public static final LabeledVariablesNamingResult EMPTY = new LabeledVariablesNamingResult(null, null); private final LabeledVariables labeledVariables; private final String unprocessed; public LabeledVariablesNamingResult(LabeledVariables labeledVariables, String unprocessed) { this.labeledVariables = labeledVariables; this.unprocessed = unprocessed; } @Override public Optional<LabeledVariables> getResult() { return Optional.ofNullable(labeledVariables); } @Override public String getUnprocessed() { return unprocessed; } }
7,863
0
Create_ds/frigga/src/main/java/com/netflix/frigga/conventions
Create_ds/frigga/src/main/java/com/netflix/frigga/conventions/labeledvariables/LabeledVariables.java
/** * Copyright 2020 Netflix, Inc. * * 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 com.netflix.frigga.conventions.labeledvariables; import java.util.Objects; /** * The legacy labeled variables that can be encoded in the details component of a name. */ public class LabeledVariables { private final String countries; private final String devPhase; private final String hardware; private final String partners; private final String revision; private final String usedBy; private final String redBlackSwap; private final String zone; public LabeledVariables(String countries, String devPhase, String hardware, String partners, String revision, String usedBy, String redBlackSwap, String zone) { this.countries = countries; this.devPhase = devPhase; this.hardware = hardware; this.partners = partners; this.revision = revision; this.usedBy = usedBy; this.redBlackSwap = redBlackSwap; this.zone = zone; } public String getCountries() { return countries; } public String getDevPhase() { return devPhase; } public String getHardware() { return hardware; } public String getPartners() { return partners; } public String getRevision() { return revision; } public String getUsedBy() { return usedBy; } public String getRedBlackSwap() { return redBlackSwap; } public String getZone() { return zone; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; LabeledVariables that = (LabeledVariables) o; return Objects.equals(countries, that.countries) && Objects.equals(devPhase, that.devPhase) && Objects.equals(hardware, that.hardware) && Objects.equals(partners, that.partners) && Objects.equals(revision, that.revision) && Objects.equals(usedBy, that.usedBy) && Objects.equals(redBlackSwap, that.redBlackSwap) && Objects.equals(zone, that.zone); } @Override public int hashCode() { return Objects.hash(countries, devPhase, hardware, partners, revision, usedBy, redBlackSwap, zone); } @Override public String toString() { return "LabeledVariables{" + "countries='" + countries + '\'' + ", devPhase='" + devPhase + '\'' + ", hardware='" + hardware + '\'' + ", partners='" + partners + '\'' + ", revision='" + revision + '\'' + ", usedBy='" + usedBy + '\'' + ", redBlackSwap='" + redBlackSwap + '\'' + ", zone='" + zone + '\'' + '}'; } }
7,864
0
Create_ds/frigga/src/main/java/com/netflix/frigga/conventions
Create_ds/frigga/src/main/java/com/netflix/frigga/conventions/sharding/ShardingNamingResult.java
/** * Copyright 2020 Netflix, Inc. * * 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 com.netflix.frigga.conventions.sharding; import com.netflix.frigga.extensions.NamingResult; import java.util.Collection; import java.util.Collections; import java.util.Map; import java.util.Optional; /** * A NamingResult for ShardingNamingConvention. * * Result is a Map of {@code shardId -> Shard}, or {@code Optional.empty} if no shards were present. * * unprocessed is the remaining portion of the freeFormDetails after no more shards were present. * * Duplicate values for a shard Id are treated as a warning. * The presence of the sharding pattern in the unprocessed text is treated as a warning. */ public class ShardingNamingResult implements NamingResult<Map<Integer, Shard>> { private final Map<Integer, Shard> result; private final String unprocessed; private final Collection<String> warnings; private final Collection<String> errors; public ShardingNamingResult(Map<Integer, Shard> result, String unprocessed, Collection<String> warnings, Collection<String> errors) { this.result = result != null && result.isEmpty() ? null : result; this.unprocessed = unprocessed == null ? "" : unprocessed; this.warnings = warnings == null || warnings.isEmpty() ? Collections.emptyList() : Collections.unmodifiableCollection(warnings); this.errors = errors == null || errors.isEmpty() ? Collections.emptyList() : Collections.unmodifiableCollection(errors); } @Override public Optional<Map<Integer, Shard>> getResult() { return Optional.ofNullable(result); } @Override public String getUnprocessed() { return unprocessed; } @Override public Collection<String> getWarnings() { return warnings; } @Override public Collection<String> getErrors() { return errors; } }
7,865
0
Create_ds/frigga/src/main/java/com/netflix/frigga/conventions
Create_ds/frigga/src/main/java/com/netflix/frigga/conventions/sharding/Shard.java
/** * Copyright 2020 Netflix, Inc. * * 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 com.netflix.frigga.conventions.sharding; import java.util.Objects; /** * A Shard is a pair with a numeric (greater than 0) id and value extracted out of the * freeFormDetails component of a Name by ShardingNamingConvention. */ public class Shard { private final Integer shardId; private final String shardValue; public Shard(Integer shardId, String shardValue) { if (Objects.requireNonNull(shardId, "shardId") < 1) { throw new IllegalArgumentException("shardId must be greater than 0"); } if (Objects.requireNonNull(shardValue, "shardValue").isEmpty()) { throw new IllegalArgumentException("shardValue must be non empty"); } this.shardId = shardId; this.shardValue = shardValue; } public Integer getShardId() { return shardId; } public String getShardValue() { return shardValue; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Shard shard = (Shard) o; return shardId.equals(shard.shardId) && shardValue.equals(shard.shardValue); } @Override public int hashCode() { return Objects.hash(shardId, shardValue); } }
7,866
0
Create_ds/frigga/src/main/java/com/netflix/frigga/conventions
Create_ds/frigga/src/main/java/com/netflix/frigga/conventions/sharding/ShardingNamingConvention.java
/** * Copyright 2020 Netflix, Inc. * * 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 com.netflix.frigga.conventions.sharding; import com.netflix.frigga.NameConstants; import com.netflix.frigga.extensions.NamingConvention; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * A NamingConvention that extracts Shards out of the freeFormDetails component of a name. * * Shards are only considered in the leading portion of the freeFormDetails, and are extracted while * present, leaving any remaining portion of the details as the unprocessed portion of the NamingResult. * * A shard has a numeric id greater than 0. * The first component of a shard value must be a non digit (leading digits get consumed into the shardId) * A shard value can contain ASCII letters, digits, as well as '.', '_', '^', and '~' * * A specification for the ShardingNamingConvention follows: * <pre> * {@code * ; the naming convention operates on free-form-details: * free-form-details = *free-form-detail-char * * ; shard extraction specification: * shards = [first-shard *additional-shard] [unprocessed] * first-shard = shard-content * additional-shard = "-" shard-content * shard-content = "x" shard * shard = shard-id shard-value * shard-id = non-zero-digit *DIGIT * shard-value = shard-value-first-char *shard-value-remaining-char * unprocessed = *free-form-detail-char * * ; character sets: * non-zero-digit = %x31-39 * shard-value-first-char = ALPHA * shard-value-remaining-char = shard-value-first-char / DIGIT * free-form-detail-char = shard-value-remaining-char / "-" * } * </pre> * * If multiple shard tokens are present with the same shardId, the last value supplied takes precedence, and * the NamingResult will contain a warning indicating that there was a collision. * * If a shard appears to be present in the unprocessed portion of the freeFormDetails, this is noted as a warning. */ public class ShardingNamingConvention implements NamingConvention<ShardingNamingResult> { private static final String SHARD_CONTENTS_REGEX = "x([1-9][0-9]*)([a-zA-Z][a-zA-Z0-9]*)(.*?)$"; private static final String VALID_SHARDS_REGEX = "(?:^|-)" + SHARD_CONTENTS_REGEX; private static final String SHARD_WARNING_REGEX = ".*?-" + SHARD_CONTENTS_REGEX; private static final Pattern SHARD_PATTERN = Pattern.compile(VALID_SHARDS_REGEX); private static final Pattern SHARD_WARNING_PATTERN = Pattern.compile(SHARD_WARNING_REGEX); @Override public ShardingNamingResult extractNamingConvention(String freeFormDetails) { Map<Integer, Shard> result = new HashMap<>(); String remaining = freeFormDetails; Matcher matcher = SHARD_PATTERN.matcher(freeFormDetails); Collection<String> warnings = new ArrayList<>(); while (matcher.matches() && !remaining.isEmpty()) { Integer shardId = Integer.parseInt(matcher.group(1)); String shardValue = matcher.group(2); Shard shard = new Shard(shardId, shardValue); Shard previous = result.put(shardId, shard); if (previous != null) { warnings.add(duplicateShardWarning(previous, shard)); } remaining = matcher.group(3); matcher.reset(remaining); } if (!remaining.isEmpty()) { Matcher warningsMatcher = SHARD_WARNING_PATTERN.matcher(remaining); if (warningsMatcher.matches() && warningsMatcher.groupCount() > 2) { warnings.add(shardInRemainingWarning(remaining, warningsMatcher.group(1), warningsMatcher.group(2))); } } return new ShardingNamingResult(result, remaining, warnings, Collections.emptyList()); } //visible for testing static String duplicateShardWarning(Shard previous, Shard current) { return String.format("duplicate shardId %s, shard value %s will be ignored in favor of %s", current.getShardId(), previous.getShardValue(), current.getShardValue()); } //visible for testing static String shardInRemainingWarning(String remaining, String shardId, String shardValue) { return String.format("detected additional shard configuration in remaining detail string %s. shard %s, value %s", remaining, shardId, shardValue); } }
7,867
0
Create_ds/frigga/src/main/java/com/netflix/frigga
Create_ds/frigga/src/main/java/com/netflix/frigga/autoscaling/AutoScalingGroupNameBuilder.java
/** * Copyright 2012 Netflix, Inc. * * 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 com.netflix.frigga.autoscaling; import com.netflix.frigga.Names; import com.netflix.frigga.NameBuilder; import com.netflix.frigga.NameConstants; import com.netflix.frigga.NameValidation; import java.util.regex.Pattern; /** * Logic for constructing the name of a new auto scaling group in Asgard. */ public class AutoScalingGroupNameBuilder extends NameBuilder { private static final Pattern CONTAINS_PUSH_PATTERN = Pattern.compile("(^|-)" + NameConstants.PUSH_FORMAT + "(-|$)"); private String appName; private String stack; private String detail; private String countries; private String devPhase; private String hardware; private String partners; private String revision; private String usedBy; private String redBlackSwap; private String zoneVar; /** * Constructs and returns the name of the auto scaling group without validation. * * @return auto scaling group name */ public String buildGroupName() { return buildGroupName(false); } /** * Construct and return the name of the auto scaling group. * * @param doValidation validate the supplied parameters before constructing the name * @return auto scaling group name */ public String buildGroupName(Boolean doValidation) { NameValidation.notEmpty(appName, "appName"); if (doValidation) { validateNames(appName, stack, countries, devPhase, hardware, partners, revision, usedBy, redBlackSwap, zoneVar); if (detail != null && !detail.isEmpty() && !NameValidation.checkNameWithHyphen(detail)) { throw new IllegalArgumentException("(Use alphanumeric characters only)"); } validateDoesNotContainPush("stack", stack); validateDoesNotContainPush("detail", detail); } // Build the labeled variables for the end of the group name. String labeledVars = ""; labeledVars += generateIfSpecified(NameConstants.COUNTRIES_KEY, countries); labeledVars += generateIfSpecified(NameConstants.DEV_PHASE_KEY, devPhase); labeledVars += generateIfSpecified(NameConstants.HARDWARE_KEY, hardware); labeledVars += generateIfSpecified(NameConstants.PARTNERS_KEY, partners); labeledVars += generateIfSpecified(NameConstants.REVISION_KEY, revision); labeledVars += generateIfSpecified(NameConstants.USED_BY_KEY, usedBy); labeledVars += generateIfSpecified(NameConstants.RED_BLACK_SWAP_KEY, redBlackSwap); labeledVars += generateIfSpecified(NameConstants.ZONE_KEY, zoneVar); String result = combineAppStackDetail(appName, stack, detail) + labeledVars; return result; } private static void validateDoesNotContainPush(String field, String name) { if (name != null && !name.isEmpty() && CONTAINS_PUSH_PATTERN.matcher(name).find()) { throw new IllegalArgumentException(field + " cannot contain a push version"); } } private static void validateNames(String... names) { for (String name : names) { if (name != null && !name.isEmpty() && !NameValidation.checkName(name)) { throw new IllegalArgumentException("(Use alphanumeric characters only)"); } } } private static String generateIfSpecified(String key, String value) { if (value != null && !value.isEmpty()) { return "-" + key + NameConstants.LABELED_VAR_SEPARATOR + value; } return ""; } public static String buildNextGroupName(String asg) { if (asg == null) throw new IllegalArgumentException("asg name must be specified"); Names parsed = Names.parseName(asg); Integer sequence = parsed.getSequence(); Integer nextSequence = new Integer((sequence == null) ? 0 : sequence.intValue() + 1); if (nextSequence.intValue() >= 1000) nextSequence = new Integer(0); // Hack return String.format("%s-v%03d", parsed.getCluster(), nextSequence); } public String getAppName() { return appName; } public void setAppName(String appName) { this.appName = appName; } public AutoScalingGroupNameBuilder withAppName(String appName) { this.appName = appName; return this; } public String getStack() { return stack; } public void setStack(String stack) { this.stack = stack; } public AutoScalingGroupNameBuilder withStack(String stack) { this.stack = stack; return this; } public String getDetail() { return detail; } public void setDetail(String detail) { this.detail = detail; } public AutoScalingGroupNameBuilder withDetail(String detail) { this.detail = detail; return this; } public String getCountries() { return countries; } public void setCountries(String countries) { this.countries = countries; } public AutoScalingGroupNameBuilder withCountries(String countries) { this.countries = countries; return this; } public String getDevPhase() { return devPhase; } public void setDevPhase(String devPhase) { this.devPhase = devPhase; } public AutoScalingGroupNameBuilder withDevPhase(String devPhase) { this.devPhase = devPhase; return this; } public String getHardware() { return hardware; } public void setHardware(String hardware) { this.hardware = hardware; } public AutoScalingGroupNameBuilder withHardware(String hardware) { this.hardware = hardware; return this; } public String getPartners() { return partners; } public void setPartners(String partners) { this.partners = partners; } public AutoScalingGroupNameBuilder withPartners(String partners) { this.partners = partners; return this; } public String getRevision() { return revision; } public void setRevision(String revision) { this.revision = revision; } public AutoScalingGroupNameBuilder withRevision(String revision) { this.revision = revision; return this; } public String getUsedBy() { return usedBy; } public void setUsedBy(String usedBy) { this.usedBy = usedBy; } public AutoScalingGroupNameBuilder withUsedBy(String usedBy) { this.usedBy = usedBy; return this; } public String getRedBlackSwap() { return redBlackSwap; } public void setRedBlackSwap(String redBlackSwap) { this.redBlackSwap = redBlackSwap; } public AutoScalingGroupNameBuilder withRedBlackSwap(String redBlackSwap) { this.redBlackSwap = redBlackSwap; return this; } public String getZoneVar() { return zoneVar; } public void setZoneVar(String zoneVar) { this.zoneVar = zoneVar; } public AutoScalingGroupNameBuilder withZoneVar(String zoneVar) { this.zoneVar = zoneVar; return this; } }
7,868
0
Create_ds/commons-validator/src/test/java/org/apache/commons
Create_ds/commons-validator/src/test/java/org/apache/commons/validator/RequiredNameTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.commons.validator; import java.io.IOException; import org.xml.sax.SAXException; /** * Performs Validation Test. */ public class RequiredNameTest extends AbstractCommonTest { /** * The key used to retrieve the set of validation * rules from the xml file. */ protected static String FORM_KEY = "nameForm"; /** * The key used to retrieve the validator action. */ protected static String ACTION = "required"; public RequiredNameTest(final String name) { super(name); } /** * Load <code>ValidatorResources</code> from * validator-name-required.xml. */ @Override protected void setUp() throws IOException, SAXException { // Load resources loadResources("RequiredNameTest-config.xml"); } @Override protected void tearDown() { } /** * Tests the required validation failure. */ public void testRequired() throws ValidatorException { // Create bean to run test on. final NameBean name = new NameBean(); // Construct validator based on the loaded resources // and the form key final Validator validator = new Validator(resources, FORM_KEY); // add the name bean to the validator as a resource // for the validations to be performed on. validator.setParameter(Validator.BEAN_PARAM, name); // Get results of the validation. // throws ValidatorException, // but we aren't catching for testing // since no validation methods we use // throw this final ValidatorResults results = validator.validate(); assertNotNull("Results are null.", results); final ValidatorResult firstNameResult = results.getValidatorResult("firstName"); final ValidatorResult lastNameResult = results.getValidatorResult("lastName"); assertNotNull("First Name ValidatorResult should not be null.", firstNameResult); assertTrue("First Name ValidatorResult should contain the '" + ACTION +"' action.", firstNameResult.containsAction(ACTION)); assertTrue("First Name ValidatorResult for the '" + ACTION +"' action should have failed.", !firstNameResult.isValid(ACTION)); assertNotNull("First Name ValidatorResult should not be null.", lastNameResult); assertTrue("Last Name ValidatorResult should contain the '" + ACTION +"' action.", lastNameResult.containsAction(ACTION)); assertTrue("Last Name ValidatorResult for the '" + ACTION +"' action should have failed.", !lastNameResult.isValid(ACTION)); } /** * Tests the required validation for first name if it is blank. */ public void testRequiredFirstNameBlank() throws ValidatorException { // Create bean to run test on. final NameBean name = new NameBean(); name.setFirstName(""); // Construct validator based on the loaded resources // and the form key final Validator validator = new Validator(resources, FORM_KEY); // add the name bean to the validator as a resource // for the validations to be performed on. validator.setParameter(Validator.BEAN_PARAM, name); // Get results of the validation. final ValidatorResults results = validator.validate(); assertNotNull("Results are null.", results); final ValidatorResult firstNameResult = results.getValidatorResult("firstName"); final ValidatorResult lastNameResult = results.getValidatorResult("lastName"); assertNotNull("First Name ValidatorResult should not be null.", firstNameResult); assertTrue("First Name ValidatorResult should contain the '" + ACTION +"' action.", firstNameResult.containsAction(ACTION)); assertTrue("First Name ValidatorResult for the '" + ACTION +"' action should have failed.", !firstNameResult.isValid(ACTION)); assertNotNull("First Name ValidatorResult should not be null.", lastNameResult); assertTrue("Last Name ValidatorResult should contain the '" + ACTION +"' action.", lastNameResult.containsAction(ACTION)); assertTrue("Last Name ValidatorResult for the '" + ACTION +"' action should have failed.", !lastNameResult.isValid(ACTION)); } /** * Tests the required validation for first name. */ public void testRequiredFirstName() throws ValidatorException { // Create bean to run test on. final NameBean name = new NameBean(); name.setFirstName("Joe"); // Construct validator based on the loaded resources // and the form key final Validator validator = new Validator(resources, FORM_KEY); // add the name bean to the validator as a resource // for the validations to be performed on. validator.setParameter(Validator.BEAN_PARAM, name); // Get results of the validation. final ValidatorResults results = validator.validate(); assertNotNull("Results are null.", results); final ValidatorResult firstNameResult = results.getValidatorResult("firstName"); final ValidatorResult lastNameResult = results.getValidatorResult("lastName"); assertNotNull("First Name ValidatorResult should not be null.", firstNameResult); assertTrue("First Name ValidatorResult should contain the '" + ACTION +"' action.", firstNameResult.containsAction(ACTION)); assertTrue("First Name ValidatorResult for the '" + ACTION +"' action should have passed.", firstNameResult.isValid(ACTION)); assertNotNull("First Name ValidatorResult should not be null.", lastNameResult); assertTrue("Last Name ValidatorResult should contain the '" + ACTION +"' action.", lastNameResult.containsAction(ACTION)); assertTrue("Last Name ValidatorResult for the '" + ACTION +"' action should have failed.", !lastNameResult.isValid(ACTION)); } /** * Tests the required validation for last name if it is blank. */ public void testRequiredLastNameBlank() throws ValidatorException { // Create bean to run test on. final NameBean name = new NameBean(); name.setLastName(""); // Construct validator based on the loaded resources // and the form key final Validator validator = new Validator(resources, FORM_KEY); // add the name bean to the validator as a resource // for the validations to be performed on. validator.setParameter(Validator.BEAN_PARAM, name); // Get results of the validation. final ValidatorResults results = validator.validate(); assertNotNull("Results are null.", results); final ValidatorResult firstNameResult = results.getValidatorResult("firstName"); final ValidatorResult lastNameResult = results.getValidatorResult("lastName"); assertNotNull("First Name ValidatorResult should not be null.", firstNameResult); assertTrue("First Name ValidatorResult should contain the '" + ACTION +"' action.", firstNameResult.containsAction(ACTION)); assertTrue("First Name ValidatorResult for the '" + ACTION +"' action should have failed.", !firstNameResult.isValid(ACTION)); assertNotNull("First Name ValidatorResult should not be null.", lastNameResult); assertTrue("Last Name ValidatorResult should contain the '" + ACTION +"' action.", lastNameResult.containsAction(ACTION)); assertTrue("Last Name ValidatorResult for the '" + ACTION +"' action should have failed.", !lastNameResult.isValid(ACTION)); } /** * Tests the required validation for last name. */ public void testRequiredLastName() throws ValidatorException { // Create bean to run test on. final NameBean name = new NameBean(); name.setLastName("Smith"); // Construct validator based on the loaded resources // and the form key final Validator validator = new Validator(resources, FORM_KEY); // add the name bean to the validator as a resource // for the validations to be performed on. validator.setParameter(Validator.BEAN_PARAM, name); // Get results of the validation. final ValidatorResults results = validator.validate(); assertNotNull("Results are null.", results); final ValidatorResult firstNameResult = results.getValidatorResult("firstName"); final ValidatorResult lastNameResult = results.getValidatorResult("lastName"); assertNotNull("First Name ValidatorResult should not be null.", firstNameResult); assertTrue("First Name ValidatorResult should contain the '" + ACTION +"' action.", firstNameResult.containsAction(ACTION)); assertTrue("First Name ValidatorResult for the '" + ACTION +"' action should have failed.", !firstNameResult.isValid(ACTION)); assertNotNull("First Name ValidatorResult should not be null.", lastNameResult); assertTrue("Last Name ValidatorResult should contain the '" + ACTION +"' action.", lastNameResult.containsAction(ACTION)); assertTrue("Last Name ValidatorResult for the '" + ACTION +"' action should have passed.", lastNameResult.isValid(ACTION)); } /** * Tests the required validation for first and last name. */ public void testRequiredName() throws ValidatorException { // Create bean to run test on. final NameBean name = new NameBean(); name.setFirstName("Joe"); name.setLastName("Smith"); // Construct validator based on the loaded resources // and the form key final Validator validator = new Validator(resources, FORM_KEY); // add the name bean to the validator as a resource // for the validations to be performed on. validator.setParameter(Validator.BEAN_PARAM, name); // Get results of the validation. final ValidatorResults results = validator.validate(); assertNotNull("Results are null.", results); final ValidatorResult firstNameResult = results.getValidatorResult("firstName"); final ValidatorResult lastNameResult = results.getValidatorResult("lastName"); assertNotNull("First Name ValidatorResult should not be null.", firstNameResult); assertTrue("First Name ValidatorResult should contain the '" + ACTION +"' action.", firstNameResult.containsAction(ACTION)); assertTrue("First Name ValidatorResult for the '" + ACTION +"' action should have passed.", firstNameResult.isValid(ACTION)); assertNotNull("First Name ValidatorResult should not be null.", lastNameResult); assertTrue("Last Name ValidatorResult should contain the '" + ACTION +"' action.", lastNameResult.containsAction(ACTION)); assertTrue("Last Name ValidatorResult for the '" + ACTION +"' action should have passed.", lastNameResult.isValid(ACTION)); } }
7,869
0
Create_ds/commons-validator/src/test/java/org/apache/commons
Create_ds/commons-validator/src/test/java/org/apache/commons/validator/AbstractCommonTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.commons.validator; import java.io.IOException; import java.io.InputStream; import org.xml.sax.SAXException; import junit.framework.TestCase; /** * Consolidates reading in XML config file into parent class. */ abstract public class AbstractCommonTest extends TestCase { /** * Resources used for validation tests. */ protected ValidatorResources resources; public AbstractCommonTest(final String string) { super(string); } /** * Load <code>ValidatorResources</code> from * validator-numeric.xml. */ protected void loadResources(final String file) throws IOException, SAXException { // Load resources try (InputStream in = this.getClass().getResourceAsStream(file)) { resources = new ValidatorResources(in); } } }
7,870
0
Create_ds/commons-validator/src/test/java/org/apache/commons
Create_ds/commons-validator/src/test/java/org/apache/commons/validator/CustomValidatorResourcesTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.commons.validator; import java.io.InputStream; import junit.framework.TestCase; /** * Test custom ValidatorResources. */ public class CustomValidatorResourcesTest extends TestCase { /** * Constructs a test case with the specified name. * @param name Name of the test */ public CustomValidatorResourcesTest(final String name) { super(name); } /** * Sets up. */ @Override protected void setUp() { } /** * Tear Down */ @Override protected void tearDown() { } /** * Test creating a custom validator resources. */ public void testCustomResources() { // Load resources InputStream in = null; try { in = this.getClass().getResourceAsStream("TestNumber-config.xml"); } catch (final Exception e) { fail("Error loading resources: " + e); } finally { try { if (in != null) { in.close(); } } catch (final Exception e) { } } } }
7,871
0
Create_ds/commons-validator/src/test/java/org/apache/commons
Create_ds/commons-validator/src/test/java/org/apache/commons/validator/AbstractNumberTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.commons.validator; import java.io.IOException; import org.xml.sax.SAXException; /** * Abstracts number unit tests methods. */ abstract public class AbstractNumberTest extends AbstractCommonTest { /** * The key used to retrieve the set of validation * rules from the xml file. */ protected String FORM_KEY; /** * The key used to retrieve the validator action. */ protected String ACTION; public AbstractNumberTest(final String name) { super(name); } /** * Load <code>ValidatorResources</code> from * validator-numeric.xml. */ @Override protected void setUp() throws IOException, SAXException { // Load resources loadResources("TestNumber-config.xml"); } @Override protected void tearDown() { } /** * Tests the number validation. */ public void testNumber() throws ValidatorException { // Create bean to run test on. final ValueBean info = new ValueBean(); info.setValue("0"); valueTest(info, true); } /** * Tests the float validation failure. */ public void testNumberFailure() throws ValidatorException { // Create bean to run test on. final ValueBean info = new ValueBean(); valueTest(info, false); } /** * Utlity class to run a test on a value. * * @param info Value to run test on. * @param passed Whether or not the test is expected to pass. */ protected void valueTest(final Object info, final boolean passed) throws ValidatorException { // Construct validator based on the loaded resources // and the form key final Validator validator = new Validator(resources, FORM_KEY); // add the name bean to the validator as a resource // for the validations to be performed on. validator.setParameter(Validator.BEAN_PARAM, info); // Get results of the validation. // throws ValidatorException, // but we aren't catching for testing // since no validation methods we use // throw this final ValidatorResults results = validator.validate(); assertNotNull("Results are null.", results); final ValidatorResult result = results.getValidatorResult("value"); assertNotNull(ACTION + " value ValidatorResult should not be null.", result); assertTrue(ACTION + " value ValidatorResult should contain the '" + ACTION + "' action.", result.containsAction(ACTION)); assertTrue(ACTION + " value ValidatorResult for the '" + ACTION + "' action should have " + (passed ? "passed" : "failed") + ".", passed ? result.isValid(ACTION) : !result.isValid(ACTION)); } }
7,872
0
Create_ds/commons-validator/src/test/java/org/apache/commons
Create_ds/commons-validator/src/test/java/org/apache/commons/validator/ValueBean.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.commons.validator; /** * Value object for storing a value to run tests on. */ public class ValueBean { protected String value; /** * Gets the value. */ public String getValue() { return value; } /** * Sets the value. */ public void setValue(final String value) { this.value = value; } }
7,873
0
Create_ds/commons-validator/src/test/java/org/apache/commons
Create_ds/commons-validator/src/test/java/org/apache/commons/validator/RetrieveFormTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.commons.validator; import java.io.IOException; import java.io.InputStream; import java.util.Locale; import org.xml.sax.SAXException; import junit.framework.TestCase; /** * Tests retrieving forms using different Locales. */ public class RetrieveFormTest extends TestCase { /** * Resources used for validation tests. */ private ValidatorResources resources; /** * Prefix for the forms. */ private static final String FORM_PREFIX = "testForm_"; /** * Prefix for the forms. */ private static final Locale CANADA_FRENCH_XXX = new Locale("fr", "CA", "XXX"); /** * Constructor for FormTest. * @param name */ public RetrieveFormTest(final String name) { super(name); } /** * Load <code>ValidatorResources</code> from multiple xml files. */ @Override protected void setUp() throws IOException, SAXException { final InputStream[] streams = { this.getClass().getResourceAsStream( "RetrieveFormTest-config.xml")}; this.resources = new ValidatorResources(streams); for (final InputStream stream : streams) { stream.close(); } } /** * Test a form defined only in the "default" formset. */ public void testDefaultForm() { final String formKey = FORM_PREFIX + "default"; // *** US locale *** checkForm(Locale.US, formKey, "default"); // *** French locale *** checkForm(Locale.FRENCH, formKey, "default"); // *** France locale *** checkForm(Locale.FRANCE, formKey, "default"); // *** Candian (English) locale *** checkForm(Locale.CANADA, formKey, "default"); // *** Candian French locale *** checkForm(Locale.CANADA_FRENCH, formKey, "default"); // *** Candian French Variant locale *** checkForm(CANADA_FRENCH_XXX, formKey, "default"); } /** * Test a form defined in the "default" formset and formsets * where just the "language" is specified. */ public void testLanguageForm() { final String formKey = FORM_PREFIX + "language"; // *** US locale *** checkForm(Locale.US, formKey, "default"); // *** French locale *** checkForm(Locale.FRENCH, formKey, "fr"); // *** France locale *** checkForm(Locale.FRANCE, formKey, "fr"); // *** Candian (English) locale *** checkForm(Locale.CANADA, formKey, "default"); // *** Candian French locale *** checkForm(Locale.CANADA_FRENCH, formKey, "fr"); // *** Candian French Variant locale *** checkForm(CANADA_FRENCH_XXX, formKey, "fr"); } /** * Test a form defined in the "default" formset, formsets * where just the "language" is specified and formset where * the language and country are specified. */ public void testLanguageCountryForm() { final String formKey = FORM_PREFIX + "language_country"; // *** US locale *** checkForm(Locale.US, formKey, "default"); // *** French locale *** checkForm(Locale.FRENCH, formKey, "fr"); // *** France locale *** checkForm(Locale.FRANCE, formKey, "fr_FR"); // *** Candian (English) locale *** checkForm(Locale.CANADA, formKey, "default"); // *** Candian French locale *** checkForm(Locale.CANADA_FRENCH, formKey, "fr_CA"); // *** Candian French Variant locale *** checkForm(CANADA_FRENCH_XXX, formKey, "fr_CA"); } /** * Test a form defined in all the formsets */ public void testLanguageCountryVariantForm() { final String formKey = FORM_PREFIX + "language_country_variant"; // *** US locale *** checkForm(Locale.US, formKey, "default"); // *** French locale *** checkForm(Locale.FRENCH, formKey, "fr"); // *** France locale *** checkForm(Locale.FRANCE, formKey, "fr_FR"); // *** Candian (English) locale *** checkForm(Locale.CANADA, formKey, "default"); // *** Candian French locale *** checkForm(Locale.CANADA_FRENCH, formKey, "fr_CA"); // *** Candian French Variant locale *** checkForm(CANADA_FRENCH_XXX, formKey, "fr_CA_XXX"); } /** * Test a form not defined */ public void testFormNotFound() { final String formKey = "INVALID_NAME"; // *** US locale *** checkFormNotFound(Locale.US, formKey); // *** French locale *** checkFormNotFound(Locale.FRENCH, formKey); // *** France locale *** checkFormNotFound(Locale.FRANCE, formKey); // *** Candian (English) locale *** checkFormNotFound(Locale.CANADA, formKey); // *** Candian French locale *** checkFormNotFound(Locale.CANADA_FRENCH, formKey); // *** Candian French Variant locale *** checkFormNotFound(CANADA_FRENCH_XXX, formKey); } private void checkForm(final Locale locale, final String formKey, final String expectedVarValue) { // Retrieve the Form final Form testForm = resources.getForm(locale, formKey); assertNotNull("Form '" +formKey+"' null for locale " + locale, testForm); // Validate the expected Form is retrieved by checking the "localeVar" // value of the field. final Field testField = testForm.getField("testProperty"); assertEquals("Incorrect Form '" + formKey + "' for locale '" + locale + "'", expectedVarValue, testField.getVarValue("localeVar")); } private void checkFormNotFound(final Locale locale, final String formKey) { // Retrieve the Form final Form testForm = resources.getForm(locale, formKey); assertNull("Form '" +formKey+"' not null for locale " + locale, testForm); } }
7,874
0
Create_ds/commons-validator/src/test/java/org/apache/commons
Create_ds/commons-validator/src/test/java/org/apache/commons/validator/EntityImportTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.commons.validator; import java.net.URL; import java.util.Locale; /** * Tests entity imports. */ public class EntityImportTest extends AbstractCommonTest { public EntityImportTest(final String name) { super(name); } /** * Tests the entity import loading the <code>byteForm</code> form. */ public void testEntityImport() throws Exception { final URL url = getClass().getResource("EntityImportTest-config.xml"); final ValidatorResources resources = new ValidatorResources(url.toExternalForm()); assertNotNull("Form should be found", resources.getForm(Locale.getDefault(), "byteForm")); } /** * Tests loading ValidatorResources from a URL */ public void testParseURL() throws Exception { final URL url = getClass().getResource("EntityImportTest-config.xml"); final ValidatorResources resources = new ValidatorResources(url); assertNotNull("Form should be found", resources.getForm(Locale.getDefault(), "byteForm")); } }
7,875
0
Create_ds/commons-validator/src/test/java/org/apache/commons
Create_ds/commons-validator/src/test/java/org/apache/commons/validator/DateTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.commons.validator; import java.io.IOException; import java.util.Locale; import org.xml.sax.SAXException; /** * Abstracts date unit tests methods. */ public class DateTest extends AbstractCommonTest { /** * The key used to retrieve the set of validation * rules from the xml file. */ protected String FORM_KEY = "dateForm"; /** * The key used to retrieve the validator action. */ protected String ACTION = "date"; public DateTest(final String name) { super(name); } /** * Load <code>ValidatorResources</code> from * validator-numeric.xml. */ @Override protected void setUp() throws IOException, SAXException { // Load resources loadResources("DateTest-config.xml"); } /** * Tests the date validation. */ public void testValidDate() throws ValidatorException { // Create bean to run test on. final ValueBean info = new ValueBean(); info.setValue("12/01/2005"); valueTest(info, true); } /** * Tests the date validation. */ public void testInvalidDate() throws ValidatorException { // Create bean to run test on. final ValueBean info = new ValueBean(); info.setValue("12/01as/2005"); valueTest(info, false); } /** * Utlity class to run a test on a value. * * @param info Value to run test on. * @param passed Whether or not the test is expected to pass. */ protected void valueTest(final Object info, final boolean passed) throws ValidatorException { // Construct validator based on the loaded resources // and the form key final Validator validator = new Validator(resources, FORM_KEY); // add the name bean to the validator as a resource // for the validations to be performed on. validator.setParameter(Validator.BEAN_PARAM, info); validator.setParameter(Validator.LOCALE_PARAM, Locale.US); // Get results of the validation. // throws ValidatorException, // but we aren't catching for testing // since no validation methods we use // throw this final ValidatorResults results = validator.validate(); assertNotNull("Results are null.", results); final ValidatorResult result = results.getValidatorResult("value"); assertNotNull(ACTION + " value ValidatorResult should not be null.", result); assertTrue(ACTION + " value ValidatorResult should contain the '" + ACTION + "' action.", result.containsAction(ACTION)); assertTrue(ACTION + " value ValidatorResult for the '" + ACTION + "' action should have " + (passed ? "passed" : "failed") + ".", passed ? result.isValid(ACTION) : !result.isValid(ACTION)); } }
7,876
0
Create_ds/commons-validator/src/test/java/org/apache/commons
Create_ds/commons-validator/src/test/java/org/apache/commons/validator/TypeBean.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.commons.validator; /** * Value object that contains different fields to test type conversion * validation. */ public class TypeBean { private String sByte; private String sShort; private String sInteger; private String sLong; private String sFloat; private String sDouble; private String sDate; private String sCreditCard; public String getByte() { return sByte; } public void setByte(final String sByte) { this.sByte = sByte; } public String getShort() { return sShort; } public void setShort(final String sShort) { this.sShort = sShort; } public String getInteger() { return sInteger; } public void setInteger(final String sInteger) { this.sInteger = sInteger; } public String getLong() { return sLong; } public void setLong(final String sLong) { this.sLong = sLong; } public String getFloat() { return sFloat; } public void setFloat(final String sFloat) { this.sFloat = sFloat; } public String getDouble() { return sDouble; } public void setDouble(final String sDouble) { this.sDouble = sDouble; } public String getDate() { return sDate; } public void setDate(final String sDate) { this.sDate = sDate; } public String getCreditCard() { return sCreditCard; } public void setCreditCard(final String sCreditCard) { this.sCreditCard = sCreditCard; } }
7,877
0
Create_ds/commons-validator/src/test/java/org/apache/commons
Create_ds/commons-validator/src/test/java/org/apache/commons/validator/ValidatorResourcesTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.commons.validator; import java.io.InputStream; import junit.framework.TestCase; /** * Test ValidatorResources. */ public class ValidatorResourcesTest extends TestCase { /** * Constructor. */ public ValidatorResourcesTest(final String name) { super(name); } /** * Test null Input Stream for Validator Resources. */ public void testNullInputStream() throws Exception { try { new ValidatorResources((InputStream)null); fail("Expected IllegalArgumentException"); } catch (final IllegalArgumentException e) { // expected result // System.out.println("Exception: " + e); } } }
7,878
0
Create_ds/commons-validator/src/test/java/org/apache/commons
Create_ds/commons-validator/src/test/java/org/apache/commons/validator/ResultPair.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.commons.validator; /** * Groups tests and expected results. */ public class ResultPair { public final String item; public final boolean valid; public ResultPair(final String item, final boolean valid) { this.item = item; this.valid = valid; // Whether the individual part of URL is valid. } }
7,879
0
Create_ds/commons-validator/src/test/java/org/apache/commons
Create_ds/commons-validator/src/test/java/org/apache/commons/validator/ValidatorTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.commons.validator; import java.text.DateFormat; import java.text.ParseException; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Locale; import org.apache.commons.validator.util.ValidatorUtils; import junit.framework.TestCase; /** * Performs Validation Test. */ public class ValidatorTest extends TestCase { public ValidatorTest(final String name) { super(name); } /** * Verify that one value generates an error and the other passes. The validation * method being tested returns an object (<code>null</code> will be considered an error). */ public void testManualObject() { // property name of the method we are validating final String property = "date"; // name of ValidatorAction final String action = "date"; final ValidatorResources resources = setupDateResources(property, action); final TestBean bean = new TestBean(); bean.setDate("2/3/1999"); final Validator validator = new Validator(resources, "testForm"); validator.setParameter(Validator.BEAN_PARAM, bean); try { final ValidatorResults results = validator.validate(); assertNotNull("Results are null.", results); final ValidatorResult result = results.getValidatorResult(property); assertNotNull("Results are null.", results); assertTrue("ValidatorResult does not contain '" + action + "' validator result.", result.containsAction(action)); assertTrue("Validation of the date formatting has failed.", result.isValid(action)); } catch (final Exception e) { fail("An exception was thrown while calling Validator.validate()"); } bean.setDate("2/30/1999"); try { final ValidatorResults results = validator.validate(); assertNotNull("Results are null.", results); final ValidatorResult result = results.getValidatorResult(property); assertNotNull("Results are null.", results); assertTrue("ValidatorResult does not contain '" + action + "' validator result.", result.containsAction(action)); assertTrue("Validation of the date formatting has passed when it should have failed.", !result.isValid(action)); } catch (final Exception e) { fail("An exception was thrown while calling Validator.validate()"); } } public void testOnlyReturnErrors() throws ValidatorException { // property name of the method we are validating final String property = "date"; // name of ValidatorAction final String action = "date"; final ValidatorResources resources = setupDateResources(property, action); final TestBean bean = new TestBean(); bean.setDate("2/3/1999"); final Validator validator = new Validator(resources, "testForm"); validator.setParameter(Validator.BEAN_PARAM, bean); ValidatorResults results = validator.validate(); assertNotNull(results); // Field passed and should be in results assertTrue(results.getPropertyNames().contains(property)); // Field passed but should not be in results validator.setOnlyReturnErrors(true); results = validator.validate(); assertFalse(results.getPropertyNames().contains(property)); } public void testOnlyValidateField() throws ValidatorException { // property name of the method we are validating final String property = "date"; // name of ValidatorAction final String action = "date"; final ValidatorResources resources = setupDateResources(property, action); final TestBean bean = new TestBean(); bean.setDate("2/3/1999"); final Validator validator = new Validator(resources, "testForm", property); validator.setParameter(Validator.BEAN_PARAM, bean); final ValidatorResults results = validator.validate(); assertNotNull(results); // Field passed and should be in results assertTrue(results.getPropertyNames().contains(property)); } private ValidatorResources setupDateResources(final String property, final String action) { final ValidatorResources resources = new ValidatorResources(); final ValidatorAction va = new ValidatorAction(); va.setName(action); va.setClassname("org.apache.commons.validator.ValidatorTest"); va.setMethod("formatDate"); va.setMethodParams("java.lang.Object,org.apache.commons.validator.Field"); final FormSet fs = new FormSet(); final Form form = new Form(); form.setName("testForm"); final Field field = new Field(); field.setProperty(property); field.setDepends(action); form.addField(field); fs.addForm(form); resources.addValidatorAction(va); resources.addFormSet(fs); resources.process(); return resources; } /** * Verify that one value generates an error and the other passes. The validation * method being tested returns a <code>boolean</code> value. */ public void testManualBoolean() { final ValidatorResources resources = new ValidatorResources(); final ValidatorAction va = new ValidatorAction(); va.setName("capLetter"); va.setClassName("org.apache.commons.validator.ValidatorTest"); va.setMethod("isCapLetter"); va.setMethodParams("java.lang.Object,org.apache.commons.validator.Field,java.util.List"); final FormSet fs = new FormSet(); final Form form = new Form(); form.setName("testForm"); final Field field = new Field(); field.setProperty("letter"); field.setDepends("capLetter"); form.addField(field); fs.addForm(form); resources.addValidatorAction(va); resources.addFormSet(fs); resources.process(); final List<?> l = new ArrayList<>(); final TestBean bean = new TestBean(); bean.setLetter("A"); final Validator validator = new Validator(resources, "testForm"); validator.setParameter(Validator.BEAN_PARAM, bean); validator.setParameter("java.util.List", l); try { validator.validate(); } catch (final Exception e) { fail("An exception was thrown while calling Validator.validate()"); } assertEquals("Validation of the letter 'A'.", 0, l.size()); l.clear(); bean.setLetter("AA"); try { validator.validate(); } catch (final Exception e) { fail("An exception was thrown while calling Validator.validate()"); } assertEquals("Validation of the letter 'AA'.", 1, l.size()); } /** * Verify that one value generates an error and the other passes. The validation * method being tested returns a <code>boolean</code> value. */ public void testManualBooleanDeprecated() { final ValidatorResources resources = new ValidatorResources(); final ValidatorAction va = new ValidatorAction(); va.setName("capLetter"); va.setClassname("org.apache.commons.validator.ValidatorTest"); va.setMethod("isCapLetter"); va.setMethodParams("java.lang.Object,org.apache.commons.validator.Field,java.util.List"); final FormSet fs = new FormSet(); final Form form = new Form(); form.setName("testForm"); final Field field = new Field(); field.setProperty("letter"); field.setDepends("capLetter"); form.addField(field); fs.addForm(form); resources.addValidatorAction(va); resources.addFormSet(fs); resources.process(); final List<?> l = new ArrayList<>(); final TestBean bean = new TestBean(); bean.setLetter("A"); final Validator validator = new Validator(resources, "testForm"); validator.setParameter(Validator.BEAN_PARAM, bean); validator.setParameter("java.util.List", l); try { validator.validate(); } catch (final Exception e) { fail("An exception was thrown while calling Validator.validate()"); } assertEquals("Validation of the letter 'A'.", 0, l.size()); l.clear(); bean.setLetter("AA"); try { validator.validate(); } catch (final Exception e) { fail("An exception was thrown while calling Validator.validate()"); } assertEquals("Validation of the letter 'AA'.", 1, l.size()); } /** * Checks if the field is one upper case letter between 'A' and 'Z'. */ public static boolean isCapLetter(final Object bean, final Field field, final List<String> l) { final String value = ValidatorUtils.getValueAsString(bean, field.getProperty()); if (value == null || value.length() != 1) { l.add("Error"); return false; } if (value.charAt(0) >= 'A' && value.charAt(0) <= 'Z') { return true; } l.add("Error"); return false; } /** * Formats a <code>String</code> to a <code>Date</code>. * The <code>Validator</code> will interpret a <code>null</code> * as validation having failed. */ public static Date formatDate(final Object bean, final Field field) { final String value = ValidatorUtils.getValueAsString(bean, field.getProperty()); Date date = null; try { final DateFormat formatter = DateFormat.getDateInstance(DateFormat.SHORT, Locale.US); formatter.setLenient(false); date = formatter.parse(value); } catch (final ParseException e) { System.out.println("ValidatorTest.formatDate() - " + e.getMessage()); } return date; } public static class TestBean { private String letter; private String date; public String getLetter() { return letter; } public void setLetter(final String letter) { this.letter = letter; } public String getDate() { return date; } public void setDate(final String date) { this.date = date; } } }
7,880
0
Create_ds/commons-validator/src/test/java/org/apache/commons
Create_ds/commons-validator/src/test/java/org/apache/commons/validator/NameBean.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.commons.validator; /** * Value object that contains a first name and last name. */ public class NameBean { protected String firstName; protected String middleName; protected String lastName; public String getFirstName() { return firstName; } public void setFirstName(final String firstName) { this.firstName = firstName; } public String getMiddleName() { return middleName; } public void setMiddleName(final String middleName) { this.middleName = middleName; } public String getLastName() { return lastName; } public void setLastName(final String lastName) { this.lastName = lastName; } }
7,881
0
Create_ds/commons-validator/src/test/java/org/apache/commons
Create_ds/commons-validator/src/test/java/org/apache/commons/validator/GenericTypeValidatorImpl.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.commons.validator; import java.util.Date; import java.util.Locale; import org.apache.commons.validator.util.ValidatorUtils; /** * Contains validation methods for different unit tests. */ public class GenericTypeValidatorImpl { /** * Checks if the field can be successfully converted to a <code>byte</code>. * * @param bean The value validation is being performed on. * @param field the field to use * @return boolean If the field can be successfully converted * to a <code>byte</code> {@code true} is returned. * Otherwise {@code false}. */ public static Byte validateByte(final Object bean, final Field field) { final String value = ValidatorUtils.getValueAsString(bean, field.getProperty()); return GenericTypeValidator.formatByte(value); } /** * Checks if the field can be successfully converted to a <code>byte</code>. * * @param bean The value validation is being performed on. * @param field the field to use * @return boolean If the field can be successfully converted * to a <code>byte</code> {@code true} is returned. * Otherwise {@code false}. */ public static Byte validateByte(final Object bean, final Field field, final Locale locale) { final String value = ValidatorUtils.getValueAsString(bean, field.getProperty()); return GenericTypeValidator.formatByte(value, locale); } /** * Checks if the field can be successfully converted to a <code>short</code>. * * @param bean The value validation is being performed on. * @param field the field to use * @return boolean If the field can be successfully converted * to a <code>short</code> {@code true} is returned. * Otherwise {@code false}. */ public static Short validateShort(final Object bean, final Field field) { final String value = ValidatorUtils.getValueAsString(bean, field.getProperty()); return GenericTypeValidator.formatShort(value); } /** * Checks if the field can be successfully converted to a <code>short</code>. * * @param bean The value validation is being performed on. * @param field the field to use * @return boolean If the field can be successfully converted * to a <code>short</code> {@code true} is returned. * Otherwise {@code false}. */ public static Short validateShort(final Object bean, final Field field, final Locale locale) { final String value = ValidatorUtils.getValueAsString(bean, field.getProperty()); return GenericTypeValidator.formatShort(value, locale); } /** * Checks if the field can be successfully converted to a <code>int</code>. * * @param bean The value validation is being performed on. * @param field the field to use * @return boolean If the field can be successfully converted * to a <code>int</code> {@code true} is returned. * Otherwise {@code false}. */ public static Integer validateInt(final Object bean, final Field field) { final String value = ValidatorUtils.getValueAsString(bean, field.getProperty()); return GenericTypeValidator.formatInt(value); } /** * Checks if the field can be successfully converted to a <code>int</code>. * * @param bean The value validation is being performed on. * @param field the field to use * @return boolean If the field can be successfully converted * to a <code>int</code> {@code true} is returned. * Otherwise {@code false}. */ public static Integer validateInt(final Object bean, final Field field, final Locale locale) { final String value = ValidatorUtils.getValueAsString(bean, field.getProperty()); return GenericTypeValidator.formatInt(value, locale); } /** * Checks if the field can be successfully converted to a <code>long</code>. * * @param bean The value validation is being performed on. * @param field the field to use * @return boolean If the field can be successfully converted * to a <code>long</code> {@code true} is returned. * Otherwise {@code false}. */ public static Long validateLong(final Object bean, final Field field) { final String value = ValidatorUtils.getValueAsString(bean, field.getProperty()); return GenericTypeValidator.formatLong(value); } /** * Checks if the field can be successfully converted to a <code>long</code>. * * @param bean The value validation is being performed on. * @param field the field to use * @return boolean If the field can be successfully converted * to a <code>long</code> {@code true} is returned. * Otherwise {@code false}. */ public static Long validateLong(final Object bean, final Field field, final Locale locale) { final String value = ValidatorUtils.getValueAsString(bean, field.getProperty()); return GenericTypeValidator.formatLong(value, locale); } /** * Checks if the field can be successfully converted to a <code>float</code>. * * @param bean The value validation is being performed on. * @param field the field to use * @return boolean If the field can be successfully converted * to a <code>float</code> {@code true} is returned. * Otherwise {@code false}. */ public static Float validateFloat(final Object bean, final Field field) { final String value = ValidatorUtils.getValueAsString(bean, field.getProperty()); return GenericTypeValidator.formatFloat(value); } /** * Checks if the field can be successfully converted to a <code>float</code>. * * @param bean The value validation is being performed on. * @param field the field to use * @return boolean If the field can be successfully converted * to a <code>float</code> {@code true} is returned. * Otherwise {@code false}. */ public static Float validateFloat(final Object bean, final Field field, final Locale locale) { final String value = ValidatorUtils.getValueAsString(bean, field.getProperty()); return GenericTypeValidator.formatFloat(value, locale); } /** * Checks if the field can be successfully converted to a <code>double</code>. * * @param bean The value validation is being performed on. * @param field the field to use * @return boolean If the field can be successfully converted * to a <code>double</code> {@code true} is returned. * Otherwise {@code false}. */ public static Double validateDouble(final Object bean, final Field field) { final String value = ValidatorUtils.getValueAsString(bean, field.getProperty()); return GenericTypeValidator.formatDouble(value); } /** * Checks if the field can be successfully converted to a <code>double</code>. * * @param bean The value validation is being performed on. * @param field the field to use * @return boolean If the field can be successfully converted * to a <code>double</code> {@code true} is returned. * Otherwise {@code false}. */ public static Double validateDouble(final Object bean, final Field field, final Locale locale) { final String value = ValidatorUtils.getValueAsString(bean, field.getProperty()); return GenericTypeValidator.formatDouble(value, locale); } /** * Checks if the field can be successfully converted to a <code>date</code>. * * @param bean The value validation is being performed on. * @param field the field to use * @return boolean If the field can be successfully converted * to a <code>date</code> {@code true} is returned. * Otherwise {@code false}. */ public static Date validateDate(final Object bean, final Field field, final Locale locale) { final String value = ValidatorUtils.getValueAsString(bean, field.getProperty()); return GenericTypeValidator.formatDate(value, locale); } /** * Checks if the field can be successfully converted to a <code>date</code>. * * @param bean The value validation is being performed on. * @param field the field to use * @return boolean If the field can be successfully converted * to a <code>date</code> {@code true} is returned. * Otherwise {@code false}. */ public static Date validateDate(final Object bean, final Field field) { final String value = ValidatorUtils.getValueAsString(bean, field.getProperty()); final String datePattern = field.getVarValue("datePattern"); final String datePatternStrict = field.getVarValue("datePatternStrict"); Date result = null; if (datePattern != null && !datePattern.isEmpty()) { result = GenericTypeValidator.formatDate(value, datePattern, false); } else if (datePatternStrict != null && !datePatternStrict.isEmpty()) { result = GenericTypeValidator.formatDate(value, datePatternStrict, true); } return result; } }
7,882
0
Create_ds/commons-validator/src/test/java/org/apache/commons
Create_ds/commons-validator/src/test/java/org/apache/commons/validator/VarTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.commons.validator; import java.io.IOException; import java.util.Locale; import org.xml.sax.SAXException; /** * Test that the new Var attributes and the * digester rule changes work. */ public class VarTest extends AbstractCommonTest { /** * The key used to retrieve the set of validation * rules from the xml file. */ protected static String FORM_KEY = "testForm"; /** * The key used to retrieve the validator action. */ protected static String ACTION = "byte"; public VarTest(final String name) { super(name); } /** * Load <code>ValidatorResources</code> from * validator-multipletest.xml. */ @Override protected void setUp() throws IOException, SAXException { // Load resources loadResources("VarTest-config.xml"); } @Override protected void tearDown() { } /** * With nothing provided, we should fail both because both are required. */ public void testVars() { final Form form = resources.getForm(Locale.getDefault(), FORM_KEY); // Get field 1 final Field field1 = form.getField("field-1"); assertNotNull("field-1 is null.", field1); assertEquals("field-1 property is wrong", "field-1", field1.getProperty()); // Get var-1-1 final Var var11 = field1.getVar("var-1-1"); assertNotNull("var-1-1 is null.", var11); assertEquals("var-1-1 name is wrong", "var-1-1", var11.getName()); assertEquals("var-1-1 value is wrong", "value-1-1", var11.getValue()); assertEquals("var-1-1 jstype is wrong", "jstype-1-1", var11.getJsType()); assertFalse("var-1-1 resource is true", var11.isResource()); assertNull("var-1-1 bundle is not null.", var11.getBundle()); // Get field 2 final Field field2 = form.getField("field-2"); assertNotNull("field-2 is null.", field2); assertEquals("field-2 property is wrong", "field-2", field2.getProperty()); // Get var-2-1 final Var var21 = field2.getVar("var-2-1"); assertNotNull("var-2-1 is null.", var21); assertEquals("var-2-1 name is wrong", "var-2-1", var21.getName()); assertEquals("var-2-1 value is wrong", "value-2-1", var21.getValue()); assertEquals("var-2-1 jstype is wrong", "jstype-2-1", var21.getJsType()); assertTrue("var-2-1 resource is false", var21.isResource()); assertEquals("var-2-1 bundle is wrong", "bundle-2-1", var21.getBundle()); // Get var-2-2 final Var var22 = field2.getVar("var-2-2"); assertNotNull("var-2-2 is null.", var22); assertEquals("var-2-2 name is wrong", "var-2-2", var22.getName()); assertEquals("var-2-2 value is wrong", "value-2-2", var22.getValue()); assertNull("var-2-2 jstype is not null", var22.getJsType()); assertFalse("var-2-2 resource is true", var22.isResource()); assertEquals("var-2-2 bundle is wrong", "bundle-2-2", var22.getBundle()); } }
7,883
0
Create_ds/commons-validator/src/test/java/org/apache/commons
Create_ds/commons-validator/src/test/java/org/apache/commons/validator/GenericValidatorTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.commons.validator; import junit.framework.TestCase; /** * Test the GenericValidator class. */ public class GenericValidatorTest extends TestCase { /** * Constructor for GenericValidatorTest. */ public GenericValidatorTest(final String name) { super(name); } public void testMinLength() { // Use 0 for line end length assertTrue("Min=5 End=0", GenericValidator.minLength("12345\n\r", 5, 0)); assertFalse("Min=6 End=0", GenericValidator.minLength("12345\n\r", 6, 0)); assertFalse("Min=7 End=0", GenericValidator.minLength("12345\n\r", 7, 0)); assertFalse("Min=8 End=0", GenericValidator.minLength("12345\n\r", 8, 0)); // Use 1 for line end length assertTrue("Min=5 End=1", GenericValidator.minLength("12345\n\r", 5, 1)); assertTrue("Min=6 End=1", GenericValidator.minLength("12345\n\r", 6, 1)); assertFalse("Min=7 End=1", GenericValidator.minLength("12345\n\r", 7, 1)); assertFalse("Min=8 End=1", GenericValidator.minLength("12345\n\r", 8, 1)); // Use 2 for line end length assertTrue("Min=5 End=2", GenericValidator.minLength("12345\n\r", 5, 2)); assertTrue("Min=6 End=2", GenericValidator.minLength("12345\n\r", 6, 2)); assertTrue("Min=7 End=2", GenericValidator.minLength("12345\n\r", 7, 2)); assertFalse("Min=8 End=2", GenericValidator.minLength("12345\n\r", 8, 2)); } public void testMaxLength() { // Use 0 for line end length assertFalse("Max=4 End=0", GenericValidator.maxLength("12345\n\r", 4, 0)); assertTrue("Max=5 End=0", GenericValidator.maxLength("12345\n\r", 5, 0)); assertTrue("Max=6 End=0", GenericValidator.maxLength("12345\n\r", 6, 0)); assertTrue("Max=7 End=0", GenericValidator.maxLength("12345\n\r", 7, 0)); // Use 1 for line end length assertFalse("Max=4 End=1", GenericValidator.maxLength("12345\n\r", 4, 1)); assertFalse("Max=5 End=1", GenericValidator.maxLength("12345\n\r", 5, 1)); assertTrue("Max=6 End=1", GenericValidator.maxLength("12345\n\r", 6, 1)); assertTrue("Max=7 End=1", GenericValidator.maxLength("12345\n\r", 7, 1)); // Use 2 for line end length assertFalse("Max=4 End=2", GenericValidator.maxLength("12345\n\r", 4, 2)); assertFalse("Max=5 End=2", GenericValidator.maxLength("12345\n\r", 5, 2)); assertFalse("Max=6 End=2", GenericValidator.maxLength("12345\n\r", 6, 2)); assertTrue("Max=7 End=2", GenericValidator.maxLength("12345\n\r", 7, 2)); } }
7,884
0
Create_ds/commons-validator/src/test/java/org/apache/commons
Create_ds/commons-validator/src/test/java/org/apache/commons/validator/CreditCardValidatorTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.commons.validator; import junit.framework.TestCase; /** * Test the CreditCardValidator class. * * @deprecated this test can be removed when the deprecated class is removed */ @Deprecated public class CreditCardValidatorTest extends TestCase { private static final String VALID_VISA = "4417123456789113"; private static final String VALID_SHORT_VISA = "4222222222222"; private static final String VALID_AMEX = "378282246310005"; private static final String VALID_MASTERCARD = "5105105105105100"; private static final String VALID_DISCOVER = "6011000990139424"; private static final String VALID_DINERS = "30569309025904"; /** * Constructor for CreditCardValidatorTest. */ public CreditCardValidatorTest(final String name) { super(name); } public void testIsValid() { CreditCardValidator ccv = new CreditCardValidator(); assertFalse(ccv.isValid(null)); assertFalse(ccv.isValid("")); assertFalse(ccv.isValid("123456789012")); // too short assertFalse(ccv.isValid("12345678901234567890")); // too long assertFalse(ccv.isValid("4417123456789112")); assertFalse(ccv.isValid("4417q23456w89113")); assertTrue(ccv.isValid(VALID_VISA)); assertTrue(ccv.isValid(VALID_SHORT_VISA)); assertTrue(ccv.isValid(VALID_AMEX)); assertTrue(ccv.isValid(VALID_MASTERCARD)); assertTrue(ccv.isValid(VALID_DISCOVER)); // disallow Visa so it should fail even with good number ccv = new CreditCardValidator(CreditCardValidator.AMEX); assertFalse(ccv.isValid("4417123456789113")); } public void testAddAllowedCardType() { final CreditCardValidator ccv = new CreditCardValidator(CreditCardValidator.NONE); // Turned off all cards so even valid numbers should fail assertFalse(ccv.isValid(VALID_VISA)); assertFalse(ccv.isValid(VALID_AMEX)); assertFalse(ccv.isValid(VALID_MASTERCARD)); assertFalse(ccv.isValid(VALID_DISCOVER)); // test our custom type ccv.addAllowedCardType(new DinersClub()); assertTrue(ccv.isValid(VALID_DINERS)); } /** * Test a custom implementation of CreditCardType. */ private static class DinersClub implements CreditCardValidator.CreditCardType { private static final String PREFIX = "300,301,302,303,304,305,"; @Override public boolean matches(final String card) { final String prefix = card.substring(0, 3) + ","; return PREFIX.contains(prefix) && card.length() == 14; } } }
7,885
0
Create_ds/commons-validator/src/test/java/org/apache/commons
Create_ds/commons-validator/src/test/java/org/apache/commons/validator/RequiredIfTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.commons.validator; import java.io.IOException; import org.xml.sax.SAXException; /** * Performs Validation Test. */ public class RequiredIfTest extends AbstractCommonTest { /** * The key used to retrieve the set of validation * rules from the xml file. */ protected static String FORM_KEY = "nameForm"; /** * The key used to retrieve the validator action. */ protected static String ACTION = "requiredif"; public RequiredIfTest(final String name) { super(name); } /** * Load <code>ValidatorResources</code> from * validator-requiredif.xml. */ @Override protected void setUp() throws IOException, SAXException { // Load resources loadResources("RequiredIfTest-config.xml"); } @Override protected void tearDown() { } /** * With nothing provided, we should pass since the fields only fail on * null if the other field is non-blank. */ public void testRequired() throws ValidatorException { // Create bean to run test on. final NameBean name = new NameBean(); // Construct validator based on the loaded resources // and the form key final Validator validator = new Validator(resources, FORM_KEY); // add the name bean to the validator as a resource // for the validations to be performed on. validator.setParameter(Validator.BEAN_PARAM, name); // Get results of the validation. // throws ValidatorException, // but we aren't catching for testing // since no validation methods we use // throw this final ValidatorResults results = validator.validate(); assertNotNull("Results are null.", results); final ValidatorResult firstNameResult = results.getValidatorResult("firstName"); final ValidatorResult lastNameResult = results.getValidatorResult("lastName"); assertNotNull("First Name ValidatorResult should not be null.", firstNameResult); assertTrue("First Name ValidatorResult should contain the '" + ACTION +"' action.", firstNameResult.containsAction(ACTION)); assertTrue("First Name ValidatorResult for the '" + ACTION +"' action should have passed.", firstNameResult.isValid(ACTION)); assertNotNull("Last Name ValidatorResult should not be null.", lastNameResult); assertTrue("Last Name ValidatorResult should contain the '" + ACTION +"' action.", lastNameResult.containsAction(ACTION)); assertTrue("Last Name ValidatorResult for the '" + ACTION +"' action should have passed.", lastNameResult.isValid(ACTION)); } /** * Tests the required validation for first name if it is blank. */ public void testRequiredFirstNameBlank() throws ValidatorException { // Create bean to run test on. final NameBean name = new NameBean(); name.setFirstName(""); name.setLastName("Test"); // Construct validator based on the loaded resources // and the form key final Validator validator = new Validator(resources, FORM_KEY); // add the name bean to the validator as a resource // for the validations to be performed on. validator.setParameter(Validator.BEAN_PARAM, name); // Get results of the validation. final ValidatorResults results = validator.validate(); assertNotNull("Results are null.", results); final ValidatorResult firstNameResult = results.getValidatorResult("firstName"); final ValidatorResult lastNameResult = results.getValidatorResult("lastName"); assertNotNull("First Name ValidatorResult should not be null.", firstNameResult); assertTrue("First Name ValidatorResult should contain the '" + ACTION +"' action.", firstNameResult.containsAction(ACTION)); assertTrue("First Name ValidatorResult for the '" + ACTION +"' action should have failed.", !firstNameResult.isValid(ACTION)); assertNotNull("Last Name ValidatorResult should not be null.", lastNameResult); assertTrue("Last Name ValidatorResult should contain the '" + ACTION +"' action.", lastNameResult.containsAction(ACTION)); assertTrue("Last Name ValidatorResult for the '" + ACTION +"' action should have passed.", lastNameResult.isValid(ACTION)); } /** * Tests the required validation for last name. */ public void testRequiredFirstName() throws ValidatorException { // Create bean to run test on. final NameBean name = new NameBean(); name.setFirstName("Test"); name.setLastName("Test"); // Construct validator based on the loaded resources // and the form key final Validator validator = new Validator(resources, FORM_KEY); // add the name bean to the validator as a resource // for the validations to be performed on. validator.setParameter(Validator.BEAN_PARAM, name); // Get results of the validation. final ValidatorResults results = validator.validate(); assertNotNull("Results are null.", results); final ValidatorResult firstNameResult = results.getValidatorResult("firstName"); final ValidatorResult lastNameResult = results.getValidatorResult("lastName"); assertNotNull("First Name ValidatorResult should not be null.", firstNameResult); assertTrue("First Name ValidatorResult should contain the '" + ACTION +"' action.", firstNameResult.containsAction(ACTION)); assertTrue("First Name ValidatorResult for the '" + ACTION +"' action should have passed.", firstNameResult.isValid(ACTION)); assertNotNull("Last Name ValidatorResult should not be null.", lastNameResult); assertTrue("Last Name ValidatorResult should contain the '" + ACTION +"' action.", lastNameResult.containsAction(ACTION)); assertTrue("Last Name ValidatorResult for the '" + ACTION +"' action should have passed.", lastNameResult.isValid(ACTION)); } /** * Tests the required validation for last name if it is blank. */ public void testRequiredLastNameBlank() throws ValidatorException { // Create bean to run test on. final NameBean name = new NameBean(); name.setFirstName("Joe"); name.setLastName(""); // Construct validator based on the loaded resources // and the form key final Validator validator = new Validator(resources, FORM_KEY); // add the name bean to the validator as a resource // for the validations to be performed on. validator.setParameter(Validator.BEAN_PARAM, name); // Get results of the validation. final ValidatorResults results = validator.validate(); assertNotNull("Results are null.", results); final ValidatorResult firstNameResult = results.getValidatorResult("firstName"); final ValidatorResult lastNameResult = results.getValidatorResult("lastName"); assertNotNull("First Name ValidatorResult should not be null.", firstNameResult); assertTrue("First Name ValidatorResult should contain the '" + ACTION +"' action.", firstNameResult.containsAction(ACTION)); assertTrue("First Name ValidatorResult for the '" + ACTION +"' action should have passed.", firstNameResult.isValid(ACTION)); assertNotNull("Last Name ValidatorResult should not be null.", lastNameResult); assertTrue("Last Name ValidatorResult should contain the '" + ACTION +"' action.", lastNameResult.containsAction(ACTION)); assertTrue("Last Name ValidatorResult for the '" + ACTION +"' action should have failed.", !lastNameResult.isValid(ACTION)); } /** * Tests the required validation for last name. */ public void testRequiredLastName() throws ValidatorException { // Create bean to run test on. final NameBean name = new NameBean(); name.setFirstName("Joe"); name.setLastName("Smith"); // Construct validator based on the loaded resources // and the form key final Validator validator = new Validator(resources, FORM_KEY); // add the name bean to the validator as a resource // for the validations to be performed on. validator.setParameter(Validator.BEAN_PARAM, name); // Get results of the validation. final ValidatorResults results = validator.validate(); assertNotNull("Results are null.", results); final ValidatorResult firstNameResult = results.getValidatorResult("firstName"); final ValidatorResult lastNameResult = results.getValidatorResult("lastName"); assertNotNull("First Name ValidatorResult should not be null.", firstNameResult); assertTrue("First Name ValidatorResult should contain the '" + ACTION +"' action.", firstNameResult.containsAction(ACTION)); assertTrue("First Name ValidatorResult for the '" + ACTION +"' action should have passed.", firstNameResult.isValid(ACTION)); assertNotNull("Last Name ValidatorResult should not be null.", lastNameResult); assertTrue("Last Name ValidatorResult should contain the '" + ACTION +"' action.", lastNameResult.containsAction(ACTION)); assertTrue("Last Name ValidatorResult for the '" + ACTION +"' action should have passed.", lastNameResult.isValid(ACTION)); } }
7,886
0
Create_ds/commons-validator/src/test/java/org/apache/commons
Create_ds/commons-validator/src/test/java/org/apache/commons/validator/LongTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.commons.validator; /** * Performs Validation Test for <code>long</code> validations. */ public class LongTest extends AbstractNumberTest { public LongTest(final String name) { super(name); FORM_KEY = "longForm"; ACTION = "long"; } /** * Tests the long validation. */ public void testLong() throws ValidatorException { // Create bean to run test on. final ValueBean info = new ValueBean(); info.setValue("0"); valueTest(info, true); } /** * Tests the long validation. */ public void testLongMin() throws ValidatorException { // Create bean to run test on. final ValueBean info = new ValueBean(); info.setValue(Long.toString(Long.MIN_VALUE)); valueTest(info, true); } /** * Tests the long validation. */ public void testLongMax() throws ValidatorException { // Create bean to run test on. final ValueBean info = new ValueBean(); info.setValue(Long.toString(Long.MAX_VALUE)); valueTest(info, true); } /** * Tests the long validation failure. */ public void testLongFailure() throws ValidatorException { // Create bean to run test on. final ValueBean info = new ValueBean(); valueTest(info, false); } /** * Tests the long validation failure. */ public void testLongBeyondMin() throws ValidatorException { // Create bean to run test on. final ValueBean info = new ValueBean(); info.setValue(Long.MIN_VALUE + "1"); valueTest(info, false); } /** * Tests the long validation failure. */ public void testLongBeyondMax() throws ValidatorException { // Create bean to run test on. final ValueBean info = new ValueBean(); info.setValue(Long.MAX_VALUE + "1"); valueTest(info, false); } }
7,887
0
Create_ds/commons-validator/src/test/java/org/apache/commons
Create_ds/commons-validator/src/test/java/org/apache/commons/validator/EmailTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.commons.validator; import java.io.IOException; import org.xml.sax.SAXException; /** * Performs Validation Test for e-mail validations. * * * @deprecated to be removed when target class is removed */ @Deprecated public class EmailTest extends AbstractCommonTest { /** * The key used to retrieve the set of validation * rules from the xml file. */ protected static String FORM_KEY = "emailForm"; /** * The key used to retrieve the validator action. */ protected static String ACTION = "email"; public EmailTest(final String name) { super(name); } /** * Load <code>ValidatorResources</code> from * validator-regexp.xml. */ @Override protected void setUp() throws IOException, SAXException { loadResources("EmailTest-config.xml"); } /** * Tests the e-mail validation. */ public void testEmail() throws ValidatorException { // Create bean to run test on. final ValueBean info = new ValueBean(); info.setValue("jsmith@apache.org"); valueTest(info, true); } /** * Tests the email validation with numeric domains. */ public void testEmailWithNumericAddress() throws ValidatorException { final ValueBean info = new ValueBean(); info.setValue("someone@[216.109.118.76]"); valueTest(info, true); info.setValue("someone@yahoo.com"); valueTest(info, true); } /** * Tests the e-mail validation. */ public void testEmailExtension() throws ValidatorException { // Create bean to run test on. final ValueBean info = new ValueBean(); info.setValue("jsmith@apache.org"); valueTest(info, true); info.setValue("jsmith@apache.com"); valueTest(info, true); info.setValue("jsmith@apache.net"); valueTest(info, true); info.setValue("jsmith@apache.info"); valueTest(info, true); info.setValue("jsmith@apache."); valueTest(info, false); info.setValue("jsmith@apache.c"); valueTest(info, false); info.setValue("someone@yahoo.museum"); valueTest(info, true); info.setValue("someone@yahoo.mu-seum"); valueTest(info, false); } /** * <p>Tests the e-mail validation with a dash in * the address.</p> */ public void testEmailWithDash() throws ValidatorException { // Create bean to run test on. final ValueBean info = new ValueBean(); info.setValue("andy.noble@data-workshop.com"); valueTest(info, true); info.setValue("andy-noble@data-workshop.-com"); valueTest(info, false); info.setValue("andy-noble@data-workshop.c-om"); valueTest(info,false); info.setValue("andy-noble@data-workshop.co-m"); valueTest(info, false); } /** * Tests the e-mail validation with a dot at the end of * the address. */ public void testEmailWithDotEnd() throws ValidatorException { // Create bean to run test on. final ValueBean info = new ValueBean(); info.setValue("andy.noble@data-workshop.com."); valueTest(info, false); } /** * Tests the e-mail validation with an RCS-noncompliant character in * the address. */ public void testEmailWithBogusCharacter() throws ValidatorException { // Create bean to run test on. final ValueBean info = new ValueBean(); info.setValue("andy.noble@\u008fdata-workshop.com"); valueTest(info, false); // The ' character is valid in an email username. info.setValue("andy.o'reilly@data-workshop.com"); valueTest(info, true); // But not in the domain name. info.setValue("andy@o'reilly.data-workshop.com"); valueTest(info, false); info.setValue("foo+bar@i.am.not.in.us.example.com"); valueTest(info, true); } /** * Tests the email validation with commas. */ public void testEmailWithCommas() throws ValidatorException { final ValueBean info = new ValueBean(); info.setValue("joeblow@apa,che.org"); valueTest(info, false); info.setValue("joeblow@apache.o,rg"); valueTest(info, false); info.setValue("joeblow@apache,org"); valueTest(info, false); } /** * Tests the email validation with spaces. */ public void testEmailWithSpaces() throws ValidatorException { final ValueBean info = new ValueBean(); info.setValue("joeblow @apache.org"); valueTest(info, false); info.setValue("joeblow@ apache.org"); valueTest(info, false); info.setValue(" joeblow@apache.org"); valueTest(info, false); info.setValue("joeblow@apache.org "); valueTest(info, false); info.setValue("joe blow@apache.org "); valueTest(info, false); info.setValue("joeblow@apa che.org "); valueTest(info, false); info.setValue("\"joe blow\"@apache.org"); valueTest(info, true); } /** * Tests the email validation with ASCII control characters. * (i.e. ASCII chars 0 - 31 and 127) */ public void testEmailWithControlChars() { final EmailValidator validator = new EmailValidator(); for (char c = 0; c < 32; c++) { assertFalse("Test control char " + (int)c, validator.isValid("foo" + c + "bar@domain.com")); } assertFalse("Test control char 127", validator.isValid("foo" + (char)127 + "bar@domain.com")); } /** * Tests the e-mail validation with a user at a TLD */ public void testEmailAtTLD() throws ValidatorException { // Create bean to run test on. final ValueBean info = new ValueBean(); info.setValue("m@de"); valueTest(info, false); final org.apache.commons.validator.routines.EmailValidator validator = org.apache.commons.validator.routines.EmailValidator.getInstance(true, true); final boolean result = validator.isValid("m@de"); assertTrue("Result should have been true", result); } /** * Test that @localhost and @localhost.localdomain * addresses aren't declared valid by default */ public void testEmailLocalhost() throws ValidatorException { final ValueBean info = new ValueBean(); info.setValue("joe@localhost"); valueTest(info, false); info.setValue("joe@localhost.localdomain"); valueTest(info, false); } /** * Write this test according to parts of RFC, as opposed to the type of character * that is being tested. * * <p><b>FIXME</b>: This test fails so disable it with a leading _ for 1.1.4 release. * The real solution is to fix the email parsing. * * @throws ValidatorException */ public void _testEmailUserName() throws ValidatorException { final ValueBean info = new ValueBean(); info.setValue("joe1blow@apache.org"); valueTest(info, true); info.setValue("joe$blow@apache.org"); valueTest(info, true); info.setValue("joe-@apache.org"); valueTest(info, true); info.setValue("joe_@apache.org"); valueTest(info, true); //UnQuoted Special characters are invalid info.setValue("joe.@apache.org"); valueTest(info, false); info.setValue("joe+@apache.org"); valueTest(info, false); info.setValue("joe!@apache.org"); valueTest(info, false); info.setValue("joe*@apache.org"); valueTest(info, false); info.setValue("joe'@apache.org"); valueTest(info, false); info.setValue("joe(@apache.org"); valueTest(info, false); info.setValue("joe)@apache.org"); valueTest(info, false); info.setValue("joe,@apache.org"); valueTest(info, false); info.setValue("joe%45@apache.org"); valueTest(info, false); info.setValue("joe;@apache.org"); valueTest(info, false); info.setValue("joe?@apache.org"); valueTest(info, false); info.setValue("joe&@apache.org"); valueTest(info, false); info.setValue("joe=@apache.org"); valueTest(info, false); //Quoted Special characters are valid info.setValue("\"joe.\"@apache.org"); valueTest(info, true); info.setValue("\"joe+\"@apache.org"); valueTest(info, true); info.setValue("\"joe!\"@apache.org"); valueTest(info, true); info.setValue("\"joe*\"@apache.org"); valueTest(info, true); info.setValue("\"joe'\"@apache.org"); valueTest(info, true); info.setValue("\"joe(\"@apache.org"); valueTest(info, true); info.setValue("\"joe)\"@apache.org"); valueTest(info, true); info.setValue("\"joe,\"@apache.org"); valueTest(info, true); info.setValue("\"joe%45\"@apache.org"); valueTest(info, true); info.setValue("\"joe;\"@apache.org"); valueTest(info, true); info.setValue("\"joe?\"@apache.org"); valueTest(info, true); info.setValue("\"joe&\"@apache.org"); valueTest(info, true); info.setValue("\"joe=\"@apache.org"); valueTest(info, true); } /** * These test values derive directly from RFC 822 & * Mail::RFC822::Address & RFC::RFC822::Address perl test.pl * For traceability don't combine these test values with other tests. */ ResultPair[] testEmailFromPerl = { new ResultPair("abigail@example.com", true), new ResultPair("abigail@example.com ", true), new ResultPair(" abigail@example.com", true), new ResultPair("abigail @example.com ", true), new ResultPair("*@example.net", true), new ResultPair("\"\\\"\"@foo.bar", true), new ResultPair("fred&barny@example.com", true), new ResultPair("---@example.com", true), new ResultPair("foo-bar@example.net", true), new ResultPair("\"127.0.0.1\"@[127.0.0.1]", true), new ResultPair("Abigail <abigail@example.com>", true), new ResultPair("Abigail<abigail@example.com>", true), new ResultPair("Abigail<@a,@b,@c:abigail@example.com>", true), new ResultPair("\"This is a phrase\"<abigail@example.com>", true), new ResultPair("\"Abigail \"<abigail@example.com>", true), new ResultPair("\"Joe & J. Harvey\" <example @Org>", true), new ResultPair("Abigail <abigail @ example.com>", true), new ResultPair("Abigail made this < abigail @ example . com >", true), new ResultPair("Abigail(the bitch)@example.com", true), new ResultPair("Abigail <abigail @ example . (bar) com >", true), new ResultPair("Abigail < (one) abigail (two) @(three)example . (bar) com (quz) >", true), new ResultPair("Abigail (foo) (((baz)(nested) (comment)) ! ) < (one) abigail (two) @(three)example . (bar) com (quz) >", true), new ResultPair("Abigail <abigail(fo\\(o)@example.com>", true), new ResultPair("Abigail <abigail(fo\\)o)@example.com> ", true), new ResultPair("(foo) abigail@example.com", true), new ResultPair("abigail@example.com (foo)", true), new ResultPair("\"Abi\\\"gail\" <abigail@example.com>", true), new ResultPair("abigail@[example.com]", true), new ResultPair("abigail@[exa\\[ple.com]", true), new ResultPair("abigail@[exa\\]ple.com]", true), new ResultPair("\":sysmail\"@ Some-Group. Some-Org", true), new ResultPair("Muhammed.(I am the greatest) Ali @(the)Vegas.WBA", true), new ResultPair("mailbox.sub1.sub2@this-domain", true), new ResultPair("sub-net.mailbox@sub-domain.domain", true), new ResultPair("name:;", true), new ResultPair("':;", true), new ResultPair("name: ;", true), new ResultPair("Alfred Neuman <Neuman@BBN-TENEXA>", true), new ResultPair("Neuman@BBN-TENEXA", true), new ResultPair("\"George, Ted\" <Shared@Group.Arpanet>", true), new ResultPair("Wilt . (the Stilt) Chamberlain@NBA.US", true), new ResultPair("Cruisers: Port@Portugal, Jones@SEA;", true), new ResultPair("$@[]", true), new ResultPair("*()@[]", true), new ResultPair("\"quoted ( brackets\" ( a comment )@example.com", true), new ResultPair("\"Joe & J. Harvey\"\\x0D\\x0A <ddd\\@ Org>", true), new ResultPair("\"Joe &\\x0D\\x0A J. Harvey\" <ddd \\@ Org>", true), new ResultPair("Gourmets: Pompous Person <WhoZiWhatZit\\@Cordon-Bleu>,\\x0D\\x0A" + " Childs\\@WGBH.Boston, \"Galloping Gourmet\"\\@\\x0D\\x0A" + " ANT.Down-Under (Australian National Television),\\x0D\\x0A" + " Cheapie\\@Discount-Liquors;", true), new ResultPair(" Just a string", false), new ResultPair("string", false), new ResultPair("(comment)", false), new ResultPair("()@example.com", false), new ResultPair("fred(&)barny@example.com", false), new ResultPair("fred\\ barny@example.com", false), new ResultPair("Abigail <abi gail @ example.com>", false), new ResultPair("Abigail <abigail(fo(o)@example.com>", false), new ResultPair("Abigail <abigail(fo)o)@example.com>", false), new ResultPair("\"Abi\"gail\" <abigail@example.com>", false), new ResultPair("abigail@[exa]ple.com]", false), new ResultPair("abigail@[exa[ple.com]", false), new ResultPair("abigail@[exaple].com]", false), new ResultPair("abigail@", false), new ResultPair("@example.com", false), new ResultPair("phrase: abigail@example.com abigail@example.com ;", false), new ResultPair("invalid�char@example.com", false) }; /** * Write this test based on perl Mail::RFC822::Address * which takes its example email address directly from RFC822 * * @throws ValidatorException * * FIXME This test fails so disable it with a leading _ for 1.1.4 release. * The real solution is to fix the email parsing. */ public void _testEmailFromPerl() throws ValidatorException { final ValueBean info = new ValueBean(); for (final ResultPair element : testEmailFromPerl) { info.setValue(element.item); valueTest(info, element.valid); } } /** * Utlity class to run a test on a value. * * @param info Value to run test on. * @param passed Whether or not the test is expected to pass. */ private void valueTest(final ValueBean info, final boolean passed) throws ValidatorException { // Construct validator based on the loaded resources // and the form key final Validator validator = new Validator(resources, FORM_KEY); // add the name bean to the validator as a resource // for the validations to be performed on. validator.setParameter(Validator.BEAN_PARAM, info); // Get results of the validation. // throws ValidatorException, // but we aren't catching for testing // since no validation methods we use // throw this final ValidatorResults results = validator.validate(); assertNotNull("Results are null.", results); final ValidatorResult result = results.getValidatorResult("value"); assertNotNull(ACTION + " value ValidatorResult should not be null.", result); assertTrue("Value "+info.getValue()+" ValidatorResult should contain the '" + ACTION +"' action.", result.containsAction(ACTION)); assertTrue("Value "+info.getValue()+"ValidatorResult for the '" + ACTION +"' action should have " + (passed ? "passed" : "failed") + ".", passed ? result.isValid(ACTION) : !result.isValid(ACTION)); } }
7,888
0
Create_ds/commons-validator/src/test/java/org/apache/commons
Create_ds/commons-validator/src/test/java/org/apache/commons/validator/GenericTypeValidatorTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.commons.validator; import java.io.IOException; import java.util.Date; import java.util.Locale; import java.util.Map; import org.xml.sax.SAXException; /** * Performs Validation Test for type validations. */ public class GenericTypeValidatorTest extends AbstractCommonTest { /** * The key used to retrieve the set of validation * rules from the xml file. */ protected static String FORM_KEY = "typeForm"; /** * The key used to retrieve the validator action. */ protected static String ACTION = "byte"; public GenericTypeValidatorTest(final String name) { super(name); } /** * Load <code>ValidatorResources</code> from * validator-type.xml. */ @Override protected void setUp() throws IOException, SAXException { // Load resources loadResources("GenericTypeValidatorTest-config.xml"); } @Override protected void tearDown() { } /** * Tests the byte validation. */ public void testType() throws ValidatorException { // Create bean to run test on. final TypeBean info = new TypeBean(); info.setByte("12"); info.setShort("129"); info.setInteger("-144"); info.setLong("88000"); info.setFloat("12.1555f"); info.setDouble("129.1551511111d"); // Construct validator based on the loaded resources // and the form key final Validator validator = new Validator(resources, FORM_KEY); // add the name bean to the validator as a resource // for the validations to be performed on. validator.setParameter(Validator.BEAN_PARAM, info); // Get results of the validation. // throws ValidatorException, // but we aren't catching for testing // since no validation methods we use // throw this final ValidatorResults results = validator.validate(); assertNotNull("Results are null.", results); final Map<String, ?> hResultValues = results.getResultValueMap(); assertTrue("Expecting byte result to be an instance of Byte.", hResultValues.get("byte") instanceof Byte); assertTrue("Expecting short result to be an instance of Short.", hResultValues.get("short") instanceof Short); assertTrue("Expecting integer result to be an instance of Integer.", hResultValues.get("integer") instanceof Integer); assertTrue("Expecting long result to be an instance of Long.", hResultValues.get("long") instanceof Long); assertTrue("Expecting float result to be an instance of Float.", hResultValues.get("float") instanceof Float); assertTrue("Expecting double result to be an instance of Double.", hResultValues.get("double") instanceof Double); for (final String key : hResultValues.keySet()) { final Object value = hResultValues.get(key); assertNotNull("value ValidatorResults.getResultValueMap() should not be null.", value); } //ValidatorResult result = results.getValidatorResult("value"); //assertNotNull(ACTION + " value ValidatorResult should not be null.", result); //assertTrue(ACTION + " value ValidatorResult should contain the '" + ACTION +"' action.", result.containsAction(ACTION)); //assertTrue(ACTION + " value ValidatorResult for the '" + ACTION +"' action should have " + (passed ? "passed" : "failed") + ".", (passed ? result.isValid(ACTION) : !result.isValid(ACTION))); } /** * Tests the us locale */ public void testUSLocale() throws ValidatorException { // Create bean to run test on. final TypeBean info = new TypeBean(); info.setByte("12"); info.setShort("129"); info.setInteger("-144"); info.setLong("88000"); info.setFloat("12.1555"); info.setDouble("129.1551511111"); info.setDate("12/21/2010"); localeTest(info, Locale.US); } /** * Tests the fr locale. */ public void testFRLocale() throws ValidatorException { // Create bean to run test on. final TypeBean info = new TypeBean(); info.setByte("12"); info.setShort("-129"); info.setInteger("1443"); info.setLong("88000"); info.setFloat("12,1555"); info.setDouble("129,1551511111"); info.setDate("21/12/2010"); final Map<String, ?> map = localeTest(info, Locale.FRENCH); assertEquals("float value not correct", 12, ((Float)map.get("float")).intValue()); assertEquals("double value not correct", 129, ((Double)map.get("double")).intValue()); } /** * Tests the locale. */ private Map<String, ?> localeTest(final TypeBean info, final Locale locale) throws ValidatorException { // Construct validator based on the loaded resources // and the form key final Validator validator = new Validator(resources, "typeLocaleForm"); // add the name bean to the validator as a resource // for the validations to be performed on. validator.setParameter(Validator.BEAN_PARAM, info); validator.setParameter("java.util.Locale", locale); // Get results of the validation. // throws ValidatorException, // but we aren't catching for testing // since no validation methods we use // throw this final ValidatorResults results = validator.validate(); assertNotNull("Results are null.", results); final Map<String, ?> hResultValues = results.getResultValueMap(); assertTrue("Expecting byte result to be an instance of Byte for locale: "+locale, hResultValues.get("byte") instanceof Byte); assertTrue("Expecting short result to be an instance of Short for locale: "+locale, hResultValues.get("short") instanceof Short); assertTrue("Expecting integer result to be an instance of Integer for locale: "+locale, hResultValues.get("integer") instanceof Integer); assertTrue("Expecting long result to be an instance of Long for locale: "+locale, hResultValues.get("long") instanceof Long); assertTrue("Expecting float result to be an instance of Float for locale: "+locale, hResultValues.get("float") instanceof Float); assertTrue("Expecting double result to be an instance of Double for locale: "+locale, hResultValues.get("double") instanceof Double); assertTrue("Expecting date result to be an instance of Date for locale: "+locale, hResultValues.get("date") instanceof Date); for (final String key : hResultValues.keySet()) { final Object value = hResultValues.get(key); assertNotNull("value ValidatorResults.getResultValueMap() should not be null for locale: "+locale, value); } return hResultValues; } }
7,889
0
Create_ds/commons-validator/src/test/java/org/apache/commons
Create_ds/commons-validator/src/test/java/org/apache/commons/validator/MultipleTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.commons.validator; import java.io.IOException; import org.xml.sax.SAXException; /** * Performs Validation Test. */ public class MultipleTest extends AbstractCommonTest { /** * The key used to retrieve the set of validation * rules from the xml file. */ protected static String FORM_KEY = "nameForm"; /** * The key used to retrieve the validator action. */ protected static String ACTION = "required"; public MultipleTest(final String name) { super(name); } /** * Load <code>ValidatorResources</code> from * validator-multipletest.xml. */ @Override protected void setUp() throws IOException, SAXException { // Load resources loadResources("MultipleTests-config.xml"); } @Override protected void tearDown() { } /** * With nothing provided, we should fail both because both are required. */ public void testBothBlank() throws ValidatorException { // Create bean to run test on. final NameBean name = new NameBean(); // Construct validator based on the loaded resources // and the form key final Validator validator = new Validator(resources, FORM_KEY); // add the name bean to the validator as a resource // for the validations to be performed on. validator.setParameter(Validator.BEAN_PARAM, name); // Get results of the validation. // throws ValidatorException, // but we aren't catching for testing // since no validation methods we use // throw this final ValidatorResults results = validator.validate(); assertNotNull("Results are null.", results); final ValidatorResult firstNameResult = results.getValidatorResult("firstName"); final ValidatorResult lastNameResult = results.getValidatorResult("lastName"); assertNotNull("First Name ValidatorResult should not be null.", firstNameResult); assertTrue("First Name ValidatorResult should contain the '" + ACTION +"' action.", firstNameResult.containsAction(ACTION)); assertTrue("First Name ValidatorResult for the '" + ACTION +"' action should have failed.", !firstNameResult.isValid(ACTION)); assertNotNull("Last Name ValidatorResult should not be null.", lastNameResult); assertTrue("Last Name ValidatorResult should contain the '" + ACTION +"' action.", lastNameResult.containsAction(ACTION)); assertTrue("Last Name ValidatorResult for the '" + ACTION +"' action should have failed.", !lastNameResult.isValid(ACTION)); assertTrue("Last Name ValidatorResults should not contain the 'int' action.", !lastNameResult.containsAction("int")); } /** * If the first name fails required, and the second test fails int, we should get two errors. */ public void testRequiredFirstNameBlankLastNameShort() throws ValidatorException { // Create bean to run test on. final NameBean name = new NameBean(); name.setFirstName(""); name.setLastName("Test"); // Construct validator based on the loaded resources // and the form key final Validator validator = new Validator(resources, FORM_KEY); // add the name bean to the validator as a resource // for the validations to be performed on. validator.setParameter(Validator.BEAN_PARAM, name); // Get results of the validation. final ValidatorResults results = validator.validate(); assertNotNull("Results are null.", results); final ValidatorResult firstNameResult = results.getValidatorResult("firstName"); final ValidatorResult lastNameResult = results.getValidatorResult("lastName"); assertNotNull("First Name ValidatorResult should not be null.", firstNameResult); assertTrue("First Name ValidatorResult should contain the '" + ACTION +"' action.", firstNameResult.containsAction(ACTION)); assertTrue("First Name ValidatorResult for the '" + ACTION +"' action should have failed.", !firstNameResult.isValid(ACTION)); assertNotNull("Last Name ValidatorResult should not be null.", lastNameResult); assertTrue("Last Name ValidatorResult should contain the 'int' action.", lastNameResult.containsAction("int")); assertTrue("Last Name ValidatorResult for the 'int' action should have failed.", !lastNameResult.isValid("int")); } /** * If the first name is there, and the last name fails int, we should get one error. */ public void testRequiredLastNameShort() throws ValidatorException { // Create bean to run test on. final NameBean name = new NameBean(); name.setFirstName("Test"); name.setLastName("Test"); // Construct validator based on the loaded resources // and the form key final Validator validator = new Validator(resources, FORM_KEY); // add the name bean to the validator as a resource // for the validations to be performed on. validator.setParameter(Validator.BEAN_PARAM, name); // Get results of the validation. final ValidatorResults results = validator.validate(); assertNotNull("Results are null.", results); final ValidatorResult firstNameResult = results.getValidatorResult("firstName"); final ValidatorResult lastNameResult = results.getValidatorResult("lastName"); assertNotNull("First Name ValidatorResult should not be null.", firstNameResult); assertTrue("First Name ValidatorResult should contain the '" + ACTION +"' action.", firstNameResult.containsAction(ACTION)); assertTrue("First Name ValidatorResult for the '" + ACTION +"' action should have passed.", firstNameResult.isValid(ACTION)); assertNotNull("Last Name ValidatorResult should not be null.", lastNameResult); assertTrue("Last Name ValidatorResult should contain the 'int' action.", lastNameResult.containsAction("int")); assertTrue("Last Name ValidatorResult for the 'int' action should have failed.", !lastNameResult.isValid("int")); } /** * If first name is ok and last name is ok and is an int, no errors. */ public void testRequiredLastNameLong() throws ValidatorException { // Create bean to run test on. final NameBean name = new NameBean(); name.setFirstName("Joe"); name.setLastName("12345678"); // Construct validator based on the loaded resources // and the form key final Validator validator = new Validator(resources, FORM_KEY); // add the name bean to the validator as a resource // for the validations to be performed on. validator.setParameter(Validator.BEAN_PARAM, name); // Get results of the validation. final ValidatorResults results = validator.validate(); assertNotNull("Results are null.", results); final ValidatorResult firstNameResult = results.getValidatorResult("firstName"); final ValidatorResult lastNameResult = results.getValidatorResult("lastName"); assertNotNull("First Name ValidatorResult should not be null.", firstNameResult); assertTrue("First Name ValidatorResult should contain the '" + ACTION +"' action.", firstNameResult.containsAction(ACTION)); assertTrue("First Name ValidatorResult for the '" + ACTION +"' action should have passed.", firstNameResult.isValid(ACTION)); assertNotNull("Last Name ValidatorResult should not be null.", lastNameResult); assertTrue("Last Name ValidatorResult should contain the 'int' action.", lastNameResult.containsAction("int")); assertTrue("Last Name ValidatorResult for the 'int' action should have passed.", lastNameResult.isValid("int")); } /** * If middle name is not there, then the required dependent test should fail. * No other tests should run * * @throws ValidatorException */ public void testFailingFirstDependentValidator() throws ValidatorException { // Create bean to run test on. final NameBean name = new NameBean(); // Construct validator based on the loaded resources // and the form key final Validator validator = new Validator(resources, FORM_KEY); // add the name bean to the validator as a resource // for the validations to be performed on. validator.setParameter(Validator.BEAN_PARAM, name); // Get results of the validation. final ValidatorResults results = validator.validate(); assertNotNull("Results are null.", results); final ValidatorResult middleNameResult = results.getValidatorResult("middleName"); assertNotNull("Middle Name ValidatorResult should not be null.", middleNameResult); assertTrue("Middle Name ValidatorResult should contain the 'required' action.", middleNameResult.containsAction("required")); assertTrue("Middle Name ValidatorResult for the 'required' action should have failed", !middleNameResult.isValid("required")); assertTrue("Middle Name ValidatorResult should not contain the 'int' action.", !middleNameResult.containsAction("int")); assertTrue("Middle Name ValidatorResult should not contain the 'positive' action.", !middleNameResult.containsAction("positive")); } /** * If middle name is there but not int, then the required dependent test * should pass, but the int dependent test should fail. No other tests should * run. * * @throws ValidatorException */ public void testFailingNextDependentValidator() throws ValidatorException { // Create bean to run test on. final NameBean name = new NameBean(); name.setMiddleName("TEST"); // Construct validator based on the loaded resources // and the form key final Validator validator = new Validator(resources, FORM_KEY); // add the name bean to the validator as a resource // for the validations to be performed on. validator.setParameter(Validator.BEAN_PARAM, name); // Get results of the validation. final ValidatorResults results = validator.validate(); assertNotNull("Results are null.", results); final ValidatorResult middleNameResult = results.getValidatorResult("middleName"); assertNotNull("Middle Name ValidatorResult should not be null.", middleNameResult); assertTrue("Middle Name ValidatorResult should contain the 'required' action.", middleNameResult.containsAction("required")); assertTrue("Middle Name ValidatorResult for the 'required' action should have passed", middleNameResult.isValid("required")); assertTrue("Middle Name ValidatorResult should contain the 'int' action.", middleNameResult.containsAction("int")); assertTrue("Middle Name ValidatorResult for the 'int' action should have failed", !middleNameResult.isValid("int")); assertTrue("Middle Name ValidatorResult should not contain the 'positive' action.", !middleNameResult.containsAction("positive")); } /** * If middle name is there and a negative int, then the required and int * dependent tests should pass, but the positive test should fail. * * @throws ValidatorException */ public void testPassingDependentsFailingMain() throws ValidatorException { // Create bean to run test on. final NameBean name = new NameBean(); name.setMiddleName("-2534"); // Construct validator based on the loaded resources // and the form key final Validator validator = new Validator(resources, FORM_KEY); // add the name bean to the validator as a resource // for the validations to be performed on. validator.setParameter(Validator.BEAN_PARAM, name); // Get results of the validation. final ValidatorResults results = validator.validate(); assertNotNull("Results are null.", results); final ValidatorResult middleNameResult = results.getValidatorResult("middleName"); assertNotNull("Middle Name ValidatorResult should not be null.", middleNameResult); assertTrue("Middle Name ValidatorResult should contain the 'required' action.", middleNameResult.containsAction("required")); assertTrue("Middle Name ValidatorResult for the 'required' action should have passed", middleNameResult.isValid("required")); assertTrue("Middle Name ValidatorResult should contain the 'int' action.", middleNameResult.containsAction("int")); assertTrue("Middle Name ValidatorResult for the 'int' action should have passed", middleNameResult.isValid("int")); assertTrue("Middle Name ValidatorResult should contain the 'positive' action.", middleNameResult.containsAction("positive")); assertTrue("Middle Name ValidatorResult for the 'positive' action should have failed", !middleNameResult.isValid("positive")); } /** * If middle name is there and a positve int, then the required and int * dependent tests should pass, and the positive test should pass. * * @throws ValidatorException */ public void testPassingDependentsPassingMain() throws ValidatorException { // Create bean to run test on. final NameBean name = new NameBean(); name.setMiddleName("2534"); // Construct validator based on the loaded resources // and the form key final Validator validator = new Validator(resources, FORM_KEY); // add the name bean to the validator as a resource // for the validations to be performed on. validator.setParameter(Validator.BEAN_PARAM, name); // Get results of the validation. final ValidatorResults results = validator.validate(); assertNotNull("Results are null.", results); final ValidatorResult middleNameResult = results.getValidatorResult("middleName"); assertNotNull("Middle Name ValidatorResult should not be null.", middleNameResult); assertTrue("Middle Name ValidatorResult should contain the 'required' action.", middleNameResult.containsAction("required")); assertTrue("Middle Name ValidatorResult for the 'required' action should have passed", middleNameResult.isValid("required")); assertTrue("Middle Name ValidatorResult should contain the 'int' action.", middleNameResult.containsAction("int")); assertTrue("Middle Name ValidatorResult for the 'int' action should have passed", middleNameResult.isValid("int")); assertTrue("Middle Name ValidatorResult should contain the 'positive' action.", middleNameResult.containsAction("positive")); assertTrue("Middle Name ValidatorResult for the 'positive' action should have passed", middleNameResult.isValid("positive")); } }
7,890
0
Create_ds/commons-validator/src/test/java/org/apache/commons
Create_ds/commons-validator/src/test/java/org/apache/commons/validator/ISBNValidatorTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.commons.validator; import junit.framework.TestCase; /** * ISBNValidator Test Case. * * @deprecated to be removed when the org.apache.commons.validator.ISBNValidator class is removed */ @Deprecated public class ISBNValidatorTest extends TestCase { private static final String VALID_ISBN_RAW = "1930110995"; private static final String VALID_ISBN_DASHES = "1-930110-99-5"; private static final String VALID_ISBN_SPACES = "1 930110 99 5"; private static final String VALID_ISBN_X = "0-201-63385-X"; private static final String INVALID_ISBN = "068-556-98-45"; public ISBNValidatorTest(final String name) { super(name); } public void testIsValid() throws Exception { final ISBNValidator validator = new ISBNValidator(); assertFalse(validator.isValid(null)); assertFalse(validator.isValid("")); assertFalse(validator.isValid("1")); assertFalse(validator.isValid("12345678901234")); assertFalse(validator.isValid("dsasdsadsads")); assertFalse(validator.isValid("535365")); assertFalse(validator.isValid("I love sparrows!")); assertFalse(validator.isValid("--1 930110 99 5")); assertFalse(validator.isValid("1 930110 99 5--")); assertFalse(validator.isValid("1 930110-99 5-")); assertTrue(validator.isValid(VALID_ISBN_RAW)); assertTrue(validator.isValid(VALID_ISBN_DASHES)); assertTrue(validator.isValid(VALID_ISBN_SPACES)); assertTrue(validator.isValid(VALID_ISBN_X)); assertFalse(validator.isValid(INVALID_ISBN)); } }
7,891
0
Create_ds/commons-validator/src/test/java/org/apache/commons
Create_ds/commons-validator/src/test/java/org/apache/commons/validator/ParameterValidatorImpl.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.commons.validator; /** * Contains validation methods for different unit tests. */ public class ParameterValidatorImpl { /** * ValidatorParameter is valid. * */ public static boolean validateParameter( final java.lang.Object bean, final org.apache.commons.validator.Form form, final org.apache.commons.validator.Field field, final org.apache.commons.validator.Validator validator, final org.apache.commons.validator.ValidatorAction action, final org.apache.commons.validator.ValidatorResults results, final java.util.Locale locale) throws Exception { return true; } }
7,892
0
Create_ds/commons-validator/src/test/java/org/apache/commons
Create_ds/commons-validator/src/test/java/org/apache/commons/validator/GenericValidatorImpl.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.commons.validator; import org.apache.commons.validator.util.ValidatorUtils; /** * Contains validation methods for different unit tests. */ public class GenericValidatorImpl { /** * Throws a runtime exception if the value of the argument is "RUNTIME", * an exception if the value of the argument is "CHECKED", and a * ValidatorException otherwise. * * @throws RuntimeException with "RUNTIME-EXCEPTION as message" * if value is "RUNTIME" * @throws Exception with "CHECKED-EXCEPTION" as message * if value is "CHECKED" * @throws ValidatorException with "VALIDATOR-EXCEPTION" as message * otherwise */ public static boolean validateRaiseException( final Object bean, final Field field) throws Exception { final String value = ValidatorUtils.getValueAsString(bean, field.getProperty()); if ("RUNTIME".equals(value)) { throw new RuntimeException("RUNTIME-EXCEPTION"); } if ("CHECKED".equals(value)) { throw new Exception("CHECKED-EXCEPTION"); } throw new ValidatorException("VALIDATOR-EXCEPTION"); } /** * Checks if the field is required. * * @return boolean If the field isn't <code>null</code> and * has a length greater than zero, {@code true} is returned. * Otherwise {@code false}. */ public static boolean validateRequired(final Object bean, final Field field) { final String value = ValidatorUtils.getValueAsString(bean, field.getProperty()); return !GenericValidator.isBlankOrNull(value); } /** * Checks if the field can be successfully converted to a <code>byte</code>. * * @param bean The value validation is being performed on. * @param field the field to use * @return boolean If the field can be successfully converted * to a <code>byte</code> {@code true} is returned. * Otherwise {@code false}. */ public static boolean validateByte(final Object bean, final Field field) { final String value = ValidatorUtils.getValueAsString(bean, field.getProperty()); return GenericValidator.isByte(value); } /** * Checks if the field can be successfully converted to a <code>short</code>. * * @param bean The value validation is being performed on. * @param field the field to use * @return boolean If the field can be successfully converted * to a <code>short</code> {@code true} is returned. * Otherwise {@code false}. */ public static boolean validateShort(final Object bean, final Field field) { final String value = ValidatorUtils.getValueAsString(bean, field.getProperty()); return GenericValidator.isShort(value); } /** * Checks if the field can be successfully converted to a <code>int</code>. * * @param bean The value validation is being performed on. * @param field the field to use * @return boolean If the field can be successfully converted * to a <code>int</code> {@code true} is returned. * Otherwise {@code false}. */ public static boolean validateInt(final Object bean, final Field field) { final String value = ValidatorUtils.getValueAsString(bean, field.getProperty()); return GenericValidator.isInt(value); } /** * Checks if field is positive assuming it is an integer * * @param bean The value validation is being performed on. * @param field Description of the field to be evaluated * @return boolean If the integer field is greater than zero, returns * true, otherwise returns false. */ public static boolean validatePositive(final Object bean , final Field field) { final String value = ValidatorUtils.getValueAsString(bean, field.getProperty()); return GenericTypeValidator.formatInt(value).intValue() > 0; } /** * Checks if the field can be successfully converted to a <code>long</code>. * * @param bean The value validation is being performed on. * @param field the field to use * @return boolean If the field can be successfully converted * to a <code>long</code> {@code true} is returned. * Otherwise {@code false}. */ public static boolean validateLong(final Object bean, final Field field) { final String value = ValidatorUtils.getValueAsString(bean, field.getProperty()); return GenericValidator.isLong(value); } /** * Checks if the field can be successfully converted to a <code>float</code>. * * @param bean The value validation is being performed on. * @param field the field to use * @return boolean If the field can be successfully converted * to a <code>float</code> {@code true} is returned. * Otherwise {@code false}. */ public static boolean validateFloat(final Object bean, final Field field) { final String value = ValidatorUtils.getValueAsString(bean, field.getProperty()); return GenericValidator.isFloat(value); } /** * Checks if the field can be successfully converted to a <code>double</code>. * * @param bean The value validation is being performed on. * @param field the field to use * @return boolean If the field can be successfully converted * to a <code>double</code> {@code true} is returned. * Otherwise {@code false}. */ public static boolean validateDouble(final Object bean, final Field field) { final String value = ValidatorUtils.getValueAsString(bean, field.getProperty()); return GenericValidator.isDouble(value); } /** * Checks if the field is an e-mail address. * * @param bean The value validation is being performed on. * @param field the field to use * @return boolean If the field is an e-mail address * {@code true} is returned. * Otherwise {@code false}. */ public static boolean validateEmail(final Object bean, final Field field) { final String value = ValidatorUtils.getValueAsString(bean, field.getProperty()); return GenericValidator.isEmail(value); } public final static String FIELD_TEST_NULL = "NULL"; public final static String FIELD_TEST_NOTNULL = "NOTNULL"; public final static String FIELD_TEST_EQUAL = "EQUAL"; public static boolean validateRequiredIf( final Object bean, final Field field, final Validator validator) { final Object form = validator.getParameterValue(Validator.BEAN_PARAM); String value = null; boolean required = false; if (isStringOrNull(bean)) { value = (String) bean; } else { value = ValidatorUtils.getValueAsString(bean, field.getProperty()); } int i = 0; String fieldJoin = "AND"; if (!GenericValidator.isBlankOrNull(field.getVarValue("fieldJoin"))) { fieldJoin = field.getVarValue("fieldJoin"); } if (fieldJoin.equalsIgnoreCase("AND")) { required = true; } while (!GenericValidator.isBlankOrNull(field.getVarValue("field[" + i + "]"))) { String dependProp = field.getVarValue("field[" + i + "]"); final String dependTest = field.getVarValue("fieldTest[" + i + "]"); final String dependTestValue = field.getVarValue("fieldValue[" + i + "]"); String dependIndexed = field.getVarValue("fieldIndexed[" + i + "]"); if (dependIndexed == null) { dependIndexed = "false"; } boolean this_required = false; if (field.isIndexed() && dependIndexed.equalsIgnoreCase("true")) { final String key = field.getKey(); if (key.contains("[") && key.contains("]")) { final String ind = key.substring(0, key.indexOf(".") + 1); dependProp = ind + dependProp; } } final String dependVal = ValidatorUtils.getValueAsString(form, dependProp); if (dependTest.equals(FIELD_TEST_NULL)) { if (dependVal != null && !dependVal.isEmpty()) { this_required = false; } else { this_required = true; } } if (dependTest.equals(FIELD_TEST_NOTNULL)) { if (dependVal != null && !dependVal.isEmpty()) { this_required = true; } else { this_required = false; } } if (dependTest.equals(FIELD_TEST_EQUAL)) { this_required = dependTestValue.equalsIgnoreCase(dependVal); } if (fieldJoin.equalsIgnoreCase("AND")) { required = required && this_required; } else { required = required || this_required; } i++; } if (required) { if (value != null && !value.isEmpty()) { return true; } return false; } return true; } private static boolean isStringOrNull(final Object o) { if (o == null) { return true; // TODO this condition is not exercised by any tests currently } return o instanceof String; } }
7,893
0
Create_ds/commons-validator/src/test/java/org/apache/commons
Create_ds/commons-validator/src/test/java/org/apache/commons/validator/IntegerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.commons.validator; /** * Performs Validation Test for <code>int</code> validations. */ public class IntegerTest extends AbstractNumberTest { public IntegerTest(final String name) { super(name); FORM_KEY = "intForm"; ACTION = "int"; } /** * Tests the int validation. */ public void testInt() throws ValidatorException { // Create bean to run test on. final ValueBean info = new ValueBean(); info.setValue("0"); valueTest(info, true); } /** * Tests the int validation. */ public void testIntMin() throws ValidatorException { // Create bean to run test on. final ValueBean info = new ValueBean(); info.setValue(Integer.toString(Integer.MIN_VALUE)); valueTest(info, true); } /** * Tests the int validation. */ public void testIntegerMax() throws ValidatorException { // Create bean to run test on. final ValueBean info = new ValueBean(); info.setValue(Integer.toString(Integer.MAX_VALUE)); valueTest(info, true); } /** * Tests the int validation failure. */ public void testIntFailure() throws ValidatorException { // Create bean to run test on. final ValueBean info = new ValueBean(); valueTest(info, false); } /** * Tests the int validation failure. */ public void testIntBeyondMin() throws ValidatorException { // Create bean to run test on. final ValueBean info = new ValueBean(); info.setValue(Integer.MIN_VALUE + "1"); valueTest(info, false); } /** * Tests the int validation failure. */ public void testIntBeyondMax() throws ValidatorException { // Create bean to run test on. final ValueBean info = new ValueBean(); info.setValue(Integer.MAX_VALUE + "1"); valueTest(info, false); } }
7,894
0
Create_ds/commons-validator/src/test/java/org/apache/commons
Create_ds/commons-validator/src/test/java/org/apache/commons/validator/FloatTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.commons.validator; /** * Performs Validation Test for <code>float</code> validations. */ public class FloatTest extends AbstractNumberTest { public FloatTest(final String name) { super(name); ACTION = "float"; FORM_KEY = "floatForm"; } /** * Tests the float validation. */ public void testFloat() throws ValidatorException { // Create bean to run test on. final ValueBean info = new ValueBean(); info.setValue("0"); valueTest(info, true); } /** * Tests the float validation. */ public void testFloatMin() throws ValidatorException { // Create bean to run test on. final ValueBean info = new ValueBean(); info.setValue(Float.toString(Float.MIN_VALUE)); valueTest(info, true); } /** * Tests the float validation. */ public void testFloatMax() throws ValidatorException { // Create bean to run test on. final ValueBean info = new ValueBean(); info.setValue(Float.toString(Float.MAX_VALUE)); valueTest(info, true); } /** * Tests the float validation failure. */ public void testFloatFailure() throws ValidatorException { // Create bean to run test on. final ValueBean info = new ValueBean(); valueTest(info, false); } }
7,895
0
Create_ds/commons-validator/src/test/java/org/apache/commons
Create_ds/commons-validator/src/test/java/org/apache/commons/validator/ExceptionTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.commons.validator; import java.io.IOException; import org.xml.sax.SAXException; /** * Performs Validation Test for exception handling. */ public class ExceptionTest extends AbstractCommonTest { /** * The key used to retrieve the set of validation * rules from the xml file. */ protected static String FORM_KEY = "exceptionForm"; /** * The key used to retrieve the validator action. */ protected static String ACTION = "raiseException"; public ExceptionTest(final String name) { super(name); } /** * Load <code>ValidatorResources</code> from * validator-exception.xml. */ @Override protected void setUp() throws IOException, SAXException { loadResources("ExceptionTest-config.xml"); } /** * Tests handling of checked exceptions - should become * ValidatorExceptions. */ public void testValidatorException() { // Create bean to run test on. final ValueBean info = new ValueBean(); info.setValue("VALIDATOR"); // Construct validator based on the loaded resources // and the form key final Validator validator = new Validator(resources, FORM_KEY); // add the name bean to the validator as a resource // for the validations to be performed on. validator.setParameter(Validator.BEAN_PARAM, info); // Get results of the validation which can throw ValidatorException try { validator.validate(); fail("ValidatorException should occur here!"); } catch (final ValidatorException expected) { assertTrue("VALIDATOR-EXCEPTION".equals(expected.getMessage())); } } /** * Tests handling of runtime exceptions. * * N.B. This test has been removed (renamed) as it currently * serves no purpose. If/When exception handling * is changed in Validator 2.0 it can be reconsidered * then. */ public void XtestRuntimeException() throws ValidatorException { // Create bean to run test on. final ValueBean info = new ValueBean(); info.setValue("RUNTIME"); // Construct validator based on the loaded resources // and the form key final Validator validator = new Validator(resources, FORM_KEY); // add the name bean to the validator as a resource // for the validations to be performed on. validator.setParameter(Validator.BEAN_PARAM, info); // Get results of the validation which can throw ValidatorException try { validator.validate(); //fail("RuntimeException should occur here!"); } catch (final RuntimeException expected) { fail("RuntimeExceptions should be treated as validation failures in Validator 1.x."); // This will be true in Validator 2.0 //assertTrue("RUNTIME-EXCEPTION".equals(expected.getMessage())); } } /** * Tests handling of checked exceptions - should become * ValidatorExceptions. * * N.B. This test has been removed (renamed) as it currently * serves no purpose. If/When exception handling * is changed in Validator 2.0 it can be reconsidered * then. */ public void XtestCheckedException() { // Create bean to run test on. final ValueBean info = new ValueBean(); info.setValue("CHECKED"); // Construct validator based on the loaded resources // and the form key final Validator validator = new Validator(resources, FORM_KEY); // add the name bean to the validator as a resource // for the validations to be performed on. validator.setParameter(Validator.BEAN_PARAM, info); // Get results of the validation which can throw ValidatorException // Tests Validator 1.x exception handling try { validator.validate(); } catch (final ValidatorException expected) { fail("Checked exceptions are not wrapped in ValidatorException in Validator 1.x."); } catch (final Exception e) { assertTrue("CHECKED-EXCEPTION".equals(e.getMessage())); } // This will be true in Validator 2.0 // try { // validator.validate(); // fail("ValidatorException should occur here!"); // } catch (ValidatorException expected) { // assertTrue("CHECKED-EXCEPTION".equals(expected.getMessage())); // } } }
7,896
0
Create_ds/commons-validator/src/test/java/org/apache/commons
Create_ds/commons-validator/src/test/java/org/apache/commons/validator/LocaleTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.commons.validator; import java.io.IOException; import java.util.Locale; import org.xml.sax.SAXException; /** * Performs Validation Test for locale validations. */ public class LocaleTest extends AbstractCommonTest { /** * The key used to retrieve the set of validation rules from the xml file. */ protected static String FORM_KEY = "nameForm"; /** The key used to retrieve the validator action. */ protected static String ACTION = "required"; /** * Constructor for the LocaleTest object * * @param name param */ public LocaleTest(final String name) { super(name); } /** * Load <code>ValidatorResources</code> from validator-locale.xml. * * @throws IOException If something goes wrong * @throws SAXException If something goes wrong */ @Override protected void setUp() throws IOException, SAXException { // Load resources loadResources("LocaleTest-config.xml"); } /** The teardown method for JUnit */ @Override protected void tearDown() { } /** * See what happens when we try to validate with a Locale, Country and * variant. Also check if the added locale validation field is getting used. * * @throws ValidatorException If something goes wrong */ public void testLocale1() throws ValidatorException { // Create bean to run test on. final NameBean name = new NameBean(); name.setFirstName(""); name.setLastName(""); valueTest(name, new Locale("en", "US", "TEST1"), false, false, false); } /** * See what happens when we try to validate with a Locale, Country and * variant * * @throws ValidatorException If something goes wrong */ public void testLocale2() throws ValidatorException { // Create bean to run test on. final NameBean name = new NameBean(); name.setFirstName(""); name.setLastName(""); valueTest(name, new Locale("en", "US", "TEST2"), true, false, true); } /** * See what happens when we try to validate with a Locale, Country and * variant * * @throws ValidatorException If something goes wrong */ public void testLocale3() throws ValidatorException { // Create bean to run test on. final NameBean name = new NameBean(); name.setFirstName(""); name.setLastName(""); valueTest(name, new Locale("en", "UK"), false, true, true); } /** * See if a locale of en_UK_TEST falls back to en_UK instead of default form * set. Bug #16920 states that this isn't happening, even though it is * passing this test. see #16920. * * @throws ValidatorException If something goes wrong */ public void testLocale4() throws ValidatorException { // Create bean to run test on. final NameBean name = new NameBean(); name.setFirstName(""); name.setLastName(""); valueTest(name, new Locale("en", "UK", "TEST"), false, true, true); } /** * See if a locale of language=en falls back to default form set. * * @throws ValidatorException If something goes wrong */ public void testLocale5() throws ValidatorException { // Create bean to run test on. final NameBean name = new NameBean(); name.setFirstName(""); name.setLastName(""); valueTest(name, new Locale("en", ""), false, false, true); } /** * Utlity class to run a test on a value. * * @param name param * @param loc param * @param firstGood param * @param lastGood param * @param middleGood param * @throws ValidatorException If something goes wrong */ private void valueTest(final Object name, final Locale loc, final boolean firstGood, final boolean lastGood, final boolean middleGood) throws ValidatorException { // Construct validator based on the loaded resources // and the form key final Validator validator = new Validator(resources, FORM_KEY); // add the name bean to the validator as a resource // for the validations to be performed on. validator.setParameter(Validator.BEAN_PARAM, name); validator.setParameter(Validator.LOCALE_PARAM, loc); // Get results of the validation. // throws ValidatorException, // but we aren't catching for testing // since no validation methods we use // throw this final ValidatorResults results = validator.validate(); assertNotNull("Results are null.", results); final ValidatorResult resultlast = results.getValidatorResult("lastName"); final ValidatorResult resultfirst = results.getValidatorResult("firstName"); final ValidatorResult resultmiddle = results.getValidatorResult("middleName"); if (firstGood) { assertNull(resultfirst); } else { assertNotNull(resultfirst); } if (middleGood) { assertNull(resultmiddle); } else { assertNotNull(resultmiddle); } if (lastGood) { assertNull(resultlast); } else { assertNotNull(resultlast); } } }
7,897
0
Create_ds/commons-validator/src/test/java/org/apache/commons
Create_ds/commons-validator/src/test/java/org/apache/commons/validator/ValidatorResultsTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.commons.validator; import java.io.IOException; import org.xml.sax.SAXException; /** * Test ValidatorResults. */ public class ValidatorResultsTest extends AbstractCommonTest { private static final String FORM_KEY = "nameForm"; private static final String firstNameField = "firstName"; private static final String middleNameField = "middleName"; private static final String lastNameField = "lastName"; private String firstName; private String middleName; private String lastName; /** * Constructor. */ public ValidatorResultsTest(final String name) { super(name); } /** * Load <code>ValidatorResources</code> from * ValidatorResultsTest-config.xml. */ @Override protected void setUp() throws IOException, SAXException { // Load resources loadResources("ValidatorResultsTest-config.xml"); // initialize values firstName = "foo"; middleName = "123"; lastName = "456"; } @Override protected void tearDown() { } /** * Test all validations ran and passed. */ public void testAllValid() throws ValidatorException { // Create bean to run test on. final NameBean bean = createNameBean(); // Validate. final ValidatorResults results = validate(bean); // Check results checkValidatorResult(results, firstNameField, "required", true); checkValidatorResult(results, middleNameField, "required", true); checkValidatorResult(results, middleNameField, "int", true); checkValidatorResult(results, middleNameField, "positive", true); checkValidatorResult(results, lastNameField, "required", true); checkValidatorResult(results, lastNameField, "int", true); } /** * Test some validations failed and some didn't run. */ public void testErrors() throws ValidatorException { middleName = "XXX"; lastName = null; // Create bean to run test on. final NameBean bean = createNameBean(); // Validate. final ValidatorResults results = validate(bean); // Check results checkValidatorResult(results, firstNameField, "required", true); checkValidatorResult(results, middleNameField, "required", true); checkValidatorResult(results, middleNameField, "int", false); checkNotRun(results, middleNameField, "positive"); checkValidatorResult(results, lastNameField, "required", false); checkNotRun(results, lastNameField, "int"); } /** * Check a validator has not been run for a field and the result. */ private void checkNotRun(final ValidatorResults results, final String field, final String action) { final ValidatorResult result = results.getValidatorResult(field); assertNotNull(field + " result", result); assertFalse(field + "[" + action + "] run", result.containsAction(action)); // System.out.println(field + "[" + action + "] not run"); } /** * Check a validator has run for a field and the result. */ private void checkValidatorResult(final ValidatorResults results, final String field, final String action, final boolean expected) { final ValidatorResult result = results.getValidatorResult(field); // System.out.println(field + "[" + action + "]=" + result.isValid(action)); assertNotNull(field + " result", result); assertTrue(field + "[" + action + "] not run", result.containsAction(action)); assertEquals(field + "[" + action + "] result", expected, result.isValid(action)); } /** * Create a NameBean. */ private NameBean createNameBean() { final NameBean name = new NameBean(); name.setFirstName(firstName); name.setMiddleName(middleName); name.setLastName(lastName); return name; } /** * Validate results. */ private ValidatorResults validate(final Object bean) throws ValidatorException { // Construct validator based on the loaded resources // and the form key final Validator validator = new Validator(resources, FORM_KEY); // add the name bean to the validator as a resource // for the validations to be performed on. validator.setParameter(Validator.BEAN_PARAM, bean); // Get results of the validation. final ValidatorResults results = validator.validate(); return results; } }
7,898
0
Create_ds/commons-validator/src/test/java/org/apache/commons
Create_ds/commons-validator/src/test/java/org/apache/commons/validator/ShortTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.commons.validator; /** * Performs Validation Test for <code>short</code> validations. */ public class ShortTest extends AbstractNumberTest { public ShortTest(final String name) { super(name); FORM_KEY = "shortForm"; ACTION = "short"; } /** * Tests the short validation. */ public void testShortMin() throws ValidatorException { // Create bean to run test on. final ValueBean info = new ValueBean(); info.setValue(Short.toString(Short.MIN_VALUE)); valueTest(info, true); } /** * Tests the short validation. */ public void testShortMax() throws ValidatorException { // Create bean to run test on. final ValueBean info = new ValueBean(); info.setValue(Short.toString(Short.MAX_VALUE)); valueTest(info, true); } /** * Tests the short validation failure. */ public void testShortBeyondMin() throws ValidatorException { // Create bean to run test on. final ValueBean info = new ValueBean(); info.setValue(Short.MIN_VALUE + "1"); valueTest(info, false); } /** * Tests the short validation failure. */ public void testShortBeyondMax() throws ValidatorException { // Create bean to run test on. final ValueBean info = new ValueBean(); info.setValue(Short.MAX_VALUE + "1"); valueTest(info, false); } }
7,899