Example usage for java.lang NoClassDefFoundError toString

List of usage examples for java.lang NoClassDefFoundError toString

Introduction

In this page you can find the example usage for java.lang NoClassDefFoundError toString.

Prototype

public String toString() 

Source Link

Document

Returns a short description of this throwable.

Usage

From source file:gdt.data.entity.facet.ExtensionHandler.java

/**
 * Get the handler instance.  // ww  w .  j a  v a  2s .c  om
 *  @param entigrator entigrator instance
 *  @param extension$ extension key
 *  @param handlerClass$ class name
 * @return handler instance.
 */

public static Object loadHandlerInstance(Entigrator entigrator, String extension$, String handlerClass$) {
    try {
        System.out.println(
                "ExtensionHandler:loadHandlerInstance:extension=" + extension$ + " handler=" + handlerClass$);

        Object obj = null;
        Class<?> cls = entigrator.getClass(handlerClass$);
        if (cls == null) {
            System.out.println("ExtensionHandler:loadHandlerInstance:1");
            Sack extension = entigrator.getEntityAtKey(extension$);
            String lib$ = extension.getElementItemAt("field", "lib");
            String jar$ = "jar:file:" + entigrator.getEntihome() + "/" + extension$ + "/" + lib$ + "!/";
            ArrayList<URL> urll = new ArrayList<URL>();
            urll.add(new URL(jar$));

            String[] sa = extension.elementListNoSorted("external");
            if (sa != null) {
                File file;
                for (String s : sa) {
                    file = new File(entigrator.getEntihome() + "/" + extension$ + "/" + s);
                    if (file.exists())
                        urll.add(new URL("jar:file:" + file.getPath() + "!/"));
                }
            }
            URL[] urls = urll.toArray(new URL[0]);
            URLClassLoader cl = URLClassLoader.newInstance(urls);

            //   Class<?>cls=entigrator.getClass(handlerClass$);

            cls = cl.loadClass(handlerClass$);

            if (cls == null) {
                System.out.println("ExtensionHandler:loadHandlerInstance:cannot load class =" + handlerClass$);
                return null;
            } else {
                //   System.out.println("ExtensionHandler:loadHandlerInstance:found class ="+handlerClass$);
                entigrator.putClass(handlerClass$, cls);
            }

        }

        try {

            Constructor[] ctors = cls.getDeclaredConstructors();
            System.out.println("ExtensionHandler:loadHandlerInstance:ctors=" + ctors.length);
            Constructor ctor = null;
            for (int i = 0; i < ctors.length; i++) {
                ctor = ctors[i];
                if (ctor.getGenericParameterTypes().length == 0)
                    break;
            }
            ctor.setAccessible(true);
            obj = ctor.newInstance();

        } catch (java.lang.NoClassDefFoundError ee) {
            System.out.println("ExtensionHandler:loadHandlerInstance:" + ee.toString());
            return null;
        }
        //if(obj!=null)
        System.out.println("ExtensionHandler:loadHandlerInstance:obj=" + obj.getClass().getName());
        return obj;
    } catch (Exception e) {
        Logger.getLogger(ExtensionHandler.class.getName()).severe(e.toString());
        return null;
    }

}

From source file:se.crisp.codekvast.agent.daemon.codebase.CodeBaseScanner.java

void findTrackedConstructors(CodeBase codeBase, Class<?> clazz) {
    if (clazz.isInterface()) {
        log.debug("Ignoring interface {}", clazz);
        return;//w w  w .j a v a2s  . com
    }

    log.debug("Analyzing {}", clazz);
    MethodAnalyzer methodAnalyzer = codeBase.getConfig().getMethodAnalyzer();
    try {
        Constructor[] declaredConstructors = clazz.getDeclaredConstructors();

        for (Constructor constructor : declaredConstructors) {
            SignatureStatus status = methodAnalyzer.apply(constructor);
            MethodSignature thisSignature = SignatureUtils.makeConstructorSignature(clazz, constructor);
            codeBase.addSignature(thisSignature, thisSignature, status);
        }

        for (Class<?> innerClass : clazz.getDeclaredClasses()) {
            findTrackedConstructors(codeBase, innerClass);
        }
    } catch (NoClassDefFoundError e) {
        log.warn("Cannot analyze {}: {}", clazz, e.toString());
    }
}

From source file:se.crisp.codekvast.agent.daemon.codebase.CodeBaseScanner.java

void findTrackedMethods(CodeBase codeBase, Set<String> packages, Set<String> excludePackages, Class<?> clazz) {
    if (clazz.isInterface()) {
        log.debug("Ignoring interface {}", clazz);
        return;/*  w  ww  . java 2s  .  com*/
    }

    log.debug("Analyzing {}", clazz);
    MethodAnalyzer methodAnalyzer = codeBase.getConfig().getMethodAnalyzer();
    try {
        Method[] declaredMethods = clazz.getDeclaredMethods();
        Method[] methods = clazz.getMethods();
        Method[] allMethods = new Method[declaredMethods.length + methods.length];
        System.arraycopy(declaredMethods, 0, allMethods, 0, declaredMethods.length);
        System.arraycopy(methods, 0, allMethods, declaredMethods.length, methods.length);

        for (Method method : allMethods) {
            SignatureStatus status = methodAnalyzer.apply(method);

            // Some AOP frameworks (e.g., Guice) push methods from a base class down to subclasses created in runtime.
            // We need to map those back to the original declaring signature, or else the original declared method will look unused.

            MethodSignature thisSignature = SignatureUtils.makeMethodSignature(clazz, method);

            MethodSignature declaringSignature = SignatureUtils.makeMethodSignature(
                    findDeclaringClass(method.getDeclaringClass(), method, packages), method);

            if (shouldExcludeSignature(declaringSignature, excludePackages)) {
                status = SignatureStatus.EXCLUDED_BY_PACKAGE_NAME;
            }
            codeBase.addSignature(thisSignature, declaringSignature, status);
        }

        for (Class<?> innerClass : clazz.getDeclaredClasses()) {
            findTrackedMethods(codeBase, packages, excludePackages, innerClass);
        }
    } catch (NoClassDefFoundError e) {
        log.warn("Cannot analyze {}: {}", clazz, e.toString());
    }
}

From source file:com.ocpsoft.pretty.faces.config.annotation.PrettyAnnotationHandler.java

/**
 * This method scans the supplied class for PrettyFaces annotations. The
 * method must be called for every class that should be scanner before
 * finally calling {@link #build(PrettyConfigBuilder)}.
 * /*from  w  w  w .jav  a2  s  .co  m*/
 * @param clazz The class to scan
 */
public void processClass(Class clazz) {

    // log class name on trace level
    if (log.isTraceEnabled()) {
        log.trace("Analyzing class: " + clazz.getName());
    }

    try {

        // scan for PrettyAnnotation class
        // returns the mapping ID, if an annotation was found
        String[] classMappingIds = processClassMappingAnnotations(clazz);

        // scan for PrettyBean annotation
        processPrettyBeanAnnotation(clazz);

        // process annotations on public methods
        for (Method method : clazz.getMethods()) {
            processMethodAnnotations(method, classMappingIds);
        }

        // loop over fields to find URLQueryParameter annotations
        for (Field field : clazz.getDeclaredFields()) {
            processFieldAnnotations(field, classMappingIds);
        }

    } catch (NoClassDefFoundError e) {
        // reference to another class unknown to the classloader
        log.debug("Unable to process class '" + clazz.getName() + "': " + e.toString());
    }

}

From source file:org.apache.axis.providers.BasicProvider.java

/**
 * Generate the WSDL for this service.//from www . j ava2s .com
 *
 * Put in the "WSDL" property of the message context
 * as a org.w3c.dom.Document
 */
public void generateWSDL(MessageContext msgContext) throws AxisFault {
    if (log.isDebugEnabled())
        log.debug("Enter: BasicProvider::generateWSDL (" + this + ")");

    /* Find the service we're invoking so we can grab it's options */
    /***************************************************************/
    SOAPService service = msgContext.getService();

    ServiceDesc serviceDesc = service.getInitializedServiceDesc(msgContext);

    // Calculate the appropriate namespaces for the WSDL we're going
    // to put out.
    //
    // If we've been explicitly told which namespaces to use, respect
    // that.  If not:
    //
    // The "interface namespace" should be either:
    // 1) The namespace of the ServiceDesc
    // 2) The transport URL (if there's no ServiceDesc ns)

    try {
        // Location URL is whatever is explicitly set in the MC
        String locationUrl = msgContext.getStrProp(MessageContext.WSDLGEN_SERV_LOC_URL);

        if (locationUrl == null) {
            // If nothing, try what's explicitly set in the ServiceDesc
            locationUrl = serviceDesc.getEndpointURL();
        }

        if (locationUrl == null) {
            // If nothing, use the actual transport URL
            locationUrl = msgContext.getStrProp(MessageContext.TRANS_URL);
        }

        // Interface namespace is whatever is explicitly set
        String interfaceNamespace = msgContext.getStrProp(MessageContext.WSDLGEN_INTFNAMESPACE);

        if (interfaceNamespace == null) {
            // If nothing, use the default namespace of the ServiceDesc
            interfaceNamespace = serviceDesc.getDefaultNamespace();
        }

        if (interfaceNamespace == null) {
            // If nothing still, use the location URL determined above
            interfaceNamespace = locationUrl;
        }

        //Do we want to do this?
        //
        //          if (locationUrl == null) {
        //              locationUrl = url;
        //          } else {
        //              try {
        //                  URL urlURL = new URL(url);
        //                  URL locationURL = new URL(locationUrl);
        //                  URL urlTemp = new URL(urlURL.getProtocol(),
        //                          locationURL.getHost(),
        //                          locationURL.getPort(),
        //                          urlURL.getFile());
        //                  interfaceNamespace += urlURL.getFile();
        //                  locationUrl = urlTemp.toString();
        //              } catch (Exception e) {
        //                  locationUrl = url;
        //                  interfaceNamespace = url;
        //              }
        //          }

        Emitter emitter = new Emitter();

        // This seems like a good idea, but in fact isn't because the
        // emitter will figure out a reasonable name (<classname>Service)
        // for the WSDL service element name.  We provide the 'alias'
        // setting to explicitly set this name. See bug 13262 for more info.
        //emitter.setServiceElementName(serviceDesc.getName());

        // service alias may be provided if exact naming is required,
        // otherwise Axis will name it according to the implementing class name
        String alias = (String) service.getOption("alias");
        if (alias != null)
            emitter.setServiceElementName(alias);

        // Set style/use
        emitter.setStyle(serviceDesc.getStyle());
        emitter.setUse(serviceDesc.getUse());

        if (serviceDesc instanceof JavaServiceDesc) {
            emitter.setClsSmart(((JavaServiceDesc) serviceDesc).getImplClass(), locationUrl);
        }

        // If a wsdl target namespace was provided, use the targetNamespace.
        // Otherwise use the interfaceNamespace constructed above.
        String targetNamespace = (String) service.getOption(OPTION_WSDL_TARGETNAMESPACE);
        if (targetNamespace == null || targetNamespace.length() == 0) {
            targetNamespace = interfaceNamespace;
        }
        emitter.setIntfNamespace(targetNamespace);

        emitter.setLocationUrl(locationUrl);
        emitter.setServiceDesc(serviceDesc);
        emitter.setTypeMappingRegistry(msgContext.getTypeMappingRegistry());

        String wsdlPortType = (String) service.getOption(OPTION_WSDL_PORTTYPE);
        String wsdlServiceElement = (String) service.getOption(OPTION_WSDL_SERVICEELEMENT);
        String wsdlServicePort = (String) service.getOption(OPTION_WSDL_SERVICEPORT);
        String wsdlInputSchema = (String) service.getOption(OPTION_WSDL_INPUTSCHEMA);
        String wsdlSoapActinMode = (String) service.getOption(OPTION_WSDL_SOAPACTION_MODE);
        String extraClasses = (String) service.getOption(OPTION_EXTRACLASSES);

        if (wsdlPortType != null && wsdlPortType.length() > 0) {
            emitter.setPortTypeName(wsdlPortType);
        }
        if (wsdlServiceElement != null && wsdlServiceElement.length() > 0) {
            emitter.setServiceElementName(wsdlServiceElement);
        }
        if (wsdlServicePort != null && wsdlServicePort.length() > 0) {
            emitter.setServicePortName(wsdlServicePort);
        }
        if (wsdlInputSchema != null && wsdlInputSchema.length() > 0) {
            emitter.setInputSchema(wsdlInputSchema);
        }
        if (wsdlSoapActinMode != null && wsdlSoapActinMode.length() > 0) {
            emitter.setSoapAction(wsdlSoapActinMode);
        }

        if (extraClasses != null && extraClasses.length() > 0) {
            emitter.setExtraClasses(extraClasses);
        }

        if (msgContext.isPropertyTrue(AxisEngine.PROP_EMIT_ALL_TYPES)) {
            emitter.setEmitAllTypes(true);
        }

        Document doc = emitter.emit(Emitter.MODE_ALL);

        msgContext.setProperty("WSDL", doc);
    } catch (NoClassDefFoundError e) {
        entLog.info(Messages.getMessage("toAxisFault00"), e);
        throw new AxisFault(e.toString(), e);
    } catch (Exception e) {
        entLog.info(Messages.getMessage("toAxisFault00"), e);
        throw AxisFault.makeFault(e);
    }

    if (log.isDebugEnabled())
        log.debug("Exit: BasicProvider::generateWSDL (" + this + ")");
}

From source file:org.apache.jmeter.protocol.http.sampler.WebServiceSampler.java

/**
 * Sample the URL using Apache SOAP driver. Implementation note for myself
 * and those that are curious. Current logic marks the end after the
 * response has been read. If read response is set to false, the buffered
 * reader will read, but do nothing with it. Essentially, the stream from
 * the server goes into the ether.//from   ww w  . j a  v a2  s  . c o m
 */
@Override
public SampleResult sample() {
    SampleResult result = new SampleResult();
    result.setSuccessful(false); // Assume it will fail
    result.setResponseCode("000"); // ditto $NON-NLS-1$
    result.setSampleLabel(getName());
    try {
        result.setURL(this.getUrl());
        org.w3c.dom.Element rdoc = createDocument();
        if (rdoc == null) {
            throw new SOAPException("Could not create document", null);
        }
        // set the response defaults
        result.setDataEncoding(ENCODING);
        result.setContentType("text/xml"); // $NON-NLS-1$
        result.setDataType(SampleResult.TEXT);
        result.setSamplerData(fileContents);// WARNING - could be large

        Envelope msgEnv = Envelope.unmarshall(rdoc);
        result.sampleStart();
        SOAPHTTPConnection spconn = null;
        // if a blank HeaderManager exists, try to
        // get the SOAPHTTPConnection. After the first
        // request, there should be a connection object
        // stored with the cookie header info.
        if (this.getHeaderManager() != null && this.getHeaderManager().getSOAPHeader() != null) {
            spconn = (SOAPHTTPConnection) this.getHeaderManager().getSOAPHeader();
        } else {
            spconn = new SOAPHTTPConnection();
        }
        spconn.setTimeout(getTimeoutAsInt());

        // set the auth. thanks to KiYun Roe for contributing the patch
        // I cleaned up the patch slightly. 5-26-05
        if (getAuthManager() != null) {
            if (getAuthManager().getAuthForURL(getUrl()) != null) {
                AuthManager authmanager = getAuthManager();
                Authorization auth = authmanager.getAuthForURL(getUrl());
                spconn.setUserName(auth.getUser());
                spconn.setPassword(auth.getPass());
            } else {
                log.warn("the URL for the auth was null." + " Username and password not set");
            }
        }
        // check the proxy
        String phost = "";
        int pport = 0;
        // if use proxy is set, we try to pick up the
        // proxy host and port from either the text
        // fields or from JMeterUtil if they were passed
        // from command line
        if (this.getUseProxy()) {
            if (this.getProxyHost().length() > 0 && this.getProxyPort() > 0) {
                phost = this.getProxyHost();
                pport = this.getProxyPort();
            } else {
                if (System.getProperty("http.proxyHost") != null
                        || System.getProperty("http.proxyPort") != null) {
                    phost = System.getProperty("http.proxyHost");
                    pport = Integer.parseInt(System.getProperty("http.proxyPort"));
                }
            }
            // if for some reason the host is blank and the port is
            // zero, the sampler will fail silently
            if (phost.length() > 0 && pport > 0) {
                spconn.setProxyHost(phost);
                spconn.setProxyPort(pport);
                if (PROXY_USER.length() > 0 && PROXY_PASS.length() > 0) {
                    spconn.setProxyUserName(PROXY_USER);
                    spconn.setProxyPassword(PROXY_PASS);
                }
            }
        }

        HeaderManager headerManager = this.getHeaderManager();
        Hashtable<String, String> reqHeaders = null;
        if (headerManager != null) {
            int size = headerManager.getHeaders().size();
            reqHeaders = new Hashtable<String, String>(size);
            for (int i = 0; i < size; i++) {
                Header header = headerManager.get(i);
                reqHeaders.put(header.getName(), header.getValue());
            }
        }
        spconn.setMaintainSession(getMaintainSession());
        spconn.send(this.getUrl(), this.getSoapAction(), reqHeaders, msgEnv, null, new SOAPContext());

        @SuppressWarnings("unchecked") // API uses raw types
        final Map<String, String> headers = spconn.getHeaders();
        result.setResponseHeaders(convertSoapHeaders(headers));

        if (this.getHeaderManager() != null) {
            this.getHeaderManager().setSOAPHeader(spconn);
        }

        BufferedReader br = null;
        if (spconn.receive() != null) {
            br = spconn.receive();
            SOAPContext sc = spconn.getResponseSOAPContext();
            // Set details from the actual response
            // Needs to be done before response can be stored
            final String contentType = sc.getContentType();
            result.setContentType(contentType);
            result.setEncodingAndType(contentType);
            int length = 0;
            if (getReadResponse()) {
                StringWriter sw = new StringWriter();
                length = IOUtils.copy(br, sw);
                result.sampleEnd();
                result.setResponseData(sw.toString().getBytes(result.getDataEncodingWithDefault()));
            } else {
                // by not reading the response
                // for real, it improves the
                // performance on slow clients
                length = br.read();
                result.sampleEnd();
                result.setResponseData(JMeterUtils.getResString("read_response_message"), null); //$NON-NLS-1$
            }
            // It is not possible to access the actual HTTP response code, so we assume no data means failure
            if (length > 0) {
                result.setSuccessful(true);
                result.setResponseCodeOK();
                result.setResponseMessageOK();
            } else {
                result.setSuccessful(false);
                result.setResponseCode("999");
                result.setResponseMessage("Empty response");
            }
        } else {
            result.sampleEnd();
            result.setSuccessful(false);
            final String contentType = spconn.getResponseSOAPContext().getContentType();
            result.setContentType(contentType);
            result.setEncodingAndType(contentType);
            result.setResponseData(
                    spconn.getResponseSOAPContext().toString().getBytes(result.getDataEncodingWithDefault()));
        }
        if (br != null) {
            br.close();
        }
        // reponse code doesn't really apply, since
        // the soap driver doesn't provide a
        // response code
    } catch (IllegalArgumentException exception) {
        String message = exception.getMessage();
        log.warn(message);
        result.setResponseMessage(message);
    } catch (SAXException exception) {
        log.warn(exception.toString());
        result.setResponseMessage(exception.getMessage());
    } catch (SOAPException exception) {
        log.warn(exception.toString());
        result.setResponseMessage(exception.getMessage());
    } catch (MalformedURLException exception) {
        String message = exception.getMessage();
        log.warn(message);
        result.setResponseMessage(message);
    } catch (IOException exception) {
        String message = exception.getMessage();
        log.warn(message);
        result.setResponseMessage(message);
    } catch (NoClassDefFoundError error) {
        log.error("Missing class: ", error);
        result.setResponseMessage(error.toString());
    } catch (Exception exception) {
        if ("javax.mail.MessagingException".equals(exception.getClass().getName())) {
            log.warn(exception.toString());
            result.setResponseMessage(exception.getMessage());
        } else {
            log.error("Problem processing the SOAP request", exception);
            result.setResponseMessage(exception.toString());
        }
    } finally {
        // Make sure the sample start time and sample end time are recorded
        // in order not to confuse the statistics calculation methods: if
        //  an error occurs and an exception is thrown it is possible that
        // the result.sampleStart() or result.sampleEnd() won't be called
        if (result.getStartTime() == 0) {
            result.sampleStart();
        }
        if (result.getEndTime() == 0) {
            result.sampleEnd();
        }
    }
    return result;
}

From source file:org.ebayopensource.turmeric.eclipse.functional.test.ft.wsdlsvc.ConsumerFromIntfTest.java

@Test
@Ignore("failing")
public void testConsumeCalculatorSvc() throws Exception {

    // Turn on the auto-build for the builders to kick-in
    SimpleTestUtil.setAutoBuilding(true);

    try {//w  w  w  . j  av a2 s. co m
        Boolean b = createServiceFromWsdl(new File(WSDL_FILE).toURI().toURL(), namespacePart);

        Assert.assertTrue(adminName + "  creation failed", b);

        StringBuffer failMessages = ProjectArtifactValidator.getErroredFileMessage();

        ProjectArtifactValidator.getErroredFileMessage().setLength(0);
        // validate artifacts
        boolean intfMatch = ServiceSetupCleanupValidate
                .validateIntfArtifacts(WorkspaceUtil.getProject(adminName), adminName);
        Assert.assertTrue(" --- Service artifacts validation failed for " + failMessages, intfMatch);

        String consumerId = "CalcConsumer_Id";
        List<String> environment = new ArrayList<String>();
        environment.add("production");
        ConsumerFromJavaParamModel model = new ConsumerFromJavaParamModel();
        model.setBaseConsumerSrcDir("src");
        model.setClientName(adminName + "Consumer");
        ArrayList<String> list = new ArrayList<String>();
        list.add(adminName);
        model.setServiceNames(list);
        model.setParentDirectory(PARENT_DIR);
        model.setConsumerId(consumerId);
        model.setEnvironments(environment);

        SimpleTestUtil.setAutoBuilding(false);

        ServiceCreator.createConsumerFromJava(model, ProgressUtil.getDefaultMonitor(null));
        SimpleTestUtil.setAutoBuilding(true);
        // Add validation for the expected artifacts and contents..
        boolean consumerMatch = ServiceSetupCleanupValidate.validateConsumerArtifacts(
                WorkspaceUtil.getProject(adminName + "Consumer"), adminName + "Consumer");

        System.out.println(failMessages.toString());
        Assert.assertTrue(" --- Service artifacts validation failed for " + failMessages.toString(),
                consumerMatch);
        ProjectArtifactValidator.getErroredFileMessage().setLength(0);

        // we know that the CC.xml or GCC.xml is the last artifact to be
        // created
        // The project exists as
        IProject consProject = WorkspaceUtil.getProject(model.getClientName());

        consProject.build(IncrementalProjectBuilder.FULL_BUILD, ProgressUtil.getDefaultMonitor(null));
        // if project build goes through, its a successful test
    } catch (NoClassDefFoundError ex) {
        assumeNoException(ex);
    } catch (Exception ex) {
        System.out.println("--- Exception in consumeCalculatorSvc() - " + ex.getMessage());
        System.out.println("--- Exception in consumeCalculatorSvc() toString - " + ex.toString());
        System.out.println("--- Exception in consumeCalculatorSvc() getCause - " + ex.getCause().getMessage());
        Assert.fail("Exception in consumeCalculatorSvc() - " + ex.getLocalizedMessage());
    }
}

From source file:org.mule.config.processors.LookupInjectionProcessor.java

public Object process(Object object) {
    Field[] fields;//from ww w  .  j  a v  a 2s . com
    try {
        fields = object.getClass().getDeclaredFields();
    } catch (NoClassDefFoundError e) {
        //Only log the warning when debugging
        if (logger.isDebugEnabled()) {
            logger.warn(e.toString());
        }
        return object;
    }
    for (int i = 0; i < fields.length; i++) {
        Field field = fields[i];
        if (field.isAnnotationPresent(Lookup.class)) {
            try {
                field.setAccessible(true);
                Object value;
                String name = field.getAnnotation(Lookup.class).value();
                boolean optional = field.getAnnotation(Lookup.class).optional();
                if (StringUtils.isBlank(name)) {
                    value = context.getRegistry().lookupObject(field.getType());
                } else {
                    value = context.getRegistry().lookupObject(name);
                }
                if (value == null && !optional) {
                    throw new RequiredValueException(AnnotationsMessages
                            .lookupNotFoundInRegistry(field.getType(), name, object.getClass()));
                }

                field.set(object, value);
            } catch (RequiredValueException e) {
                throw e;
            } catch (Exception e) {
                throw new RequiredValueException(AnnotationsMessages.lookupFailedSeePreviousException(object),
                        e);
            }
        }
    }
    return object;
}

From source file:org.mule.module.jpa.PersistenceContextProcessor.java

public Object process(Object object) {
    Field[] fields;/*from  ww w  .java 2  s. co  m*/
    try {
        fields = object.getClass().getDeclaredFields();
    } catch (NoClassDefFoundError e) {
        if (logger.isDebugEnabled()) {
            logger.warn(e.toString());
        }
        return object;
    }
    for (Field field : fields) {
        if (field.isAnnotationPresent(PersistenceContext.class)) {
            field.setAccessible(true);
            try {
                if (field.get(object) == null) {
                    EntityManagerFactory factory = muleContext.getRegistry()
                            .lookupObject(EntityManagerFactory.class);

                    if (factory == null) {
                        throw new JPAException(
                                "Couldn't find an EntityManagerFactory in the registry to inject");
                    }
                    field.set(object, new MuleEntityManager(factory));
                } else {
                    logger.warn("The PersistenceContext has already been injected");
                }
            } catch (RequiredValueException e) {
                throw e;
            } catch (Exception e) {
                throw new RequiredValueException(AnnotationsMessages.lookupFailedSeePreviousException(object),
                        e);
            }
        }
    }
    return object;
}

From source file:ru.medved.json.wssoap.WebServiceSampler.java

/**
 * Sample the URL using Apache SOAP driver. Implementation note for myself
 * and those that are curious. Current logic marks the end after the
 * response has been read. If read response is set to false, the buffered
 * reader will read, but do nothing with it. Essentially, the stream from
 * the server goes into the ether./*from  w  ww  .  j a v  a  2 s  .  c o m*/
 */
@Override
public SampleResult sample() {
    SampleResult result = new SampleResult();
    result.setSuccessful(false); // Assume it will fail
    result.setResponseCode("000"); // ditto $NON-NLS-1$
    result.setSampleLabel(getName());
    try {
        result.setURL(this.getUrl());
        org.w3c.dom.Element rdoc = createDocument();
        if (rdoc == null) {
            throw new SOAPException("Could not create document", null);
        }
        // set the response defaults
        result.setDataEncoding(ENCODING);
        result.setContentType("text/xml"); // $NON-NLS-1$
        result.setDataType(SampleResult.TEXT);
        result.setSamplerData(fileContents);// WARNING - could be large

        Envelope msgEnv = Envelope.unmarshall(rdoc);
        // create a new message
        Message msg = new Message();
        result.sampleStart();
        SOAPHTTPConnection spconn = null;
        // if a blank HeaderManager exists, try to
        // get the SOAPHTTPConnection. After the first
        // request, there should be a connection object
        // stored with the cookie header info.
        if (this.getHeaderManager() != null && this.getHeaderManager().getSOAPHeader() != null) {
            spconn = (SOAPHTTPConnection) this.getHeaderManager().getSOAPHeader();
        } else {
            spconn = new SOAPHTTPConnection();
        }

        spconn.setTimeout(getTimeoutAsInt());

        // set the auth. thanks to KiYun Roe for contributing the patch
        // I cleaned up the patch slightly. 5-26-05
        if (getAuthManager() != null) {
            if (getAuthManager().getAuthForURL(getUrl()) != null) {
                AuthManager authmanager = getAuthManager();
                Authorization auth = authmanager.getAuthForURL(getUrl());
                spconn.setUserName(auth.getUser());
                spconn.setPassword(auth.getPass());
            } else {
                log.warn("the URL for the auth was null." + " Username and password not set");
            }
        }
        // check the proxy
        String phost = "";
        int pport = 0;
        // if use proxy is set, we try to pick up the
        // proxy host and port from either the text
        // fields or from JMeterUtil if they were passed
        // from command line
        if (this.getUseProxy()) {
            if (this.getProxyHost().length() > 0 && this.getProxyPort() > 0) {
                phost = this.getProxyHost();
                pport = this.getProxyPort();
            } else {
                if (System.getProperty("http.proxyHost") != null
                        || System.getProperty("http.proxyPort") != null) {
                    phost = System.getProperty("http.proxyHost");
                    pport = Integer.parseInt(System.getProperty("http.proxyPort"));
                }
            }
            // if for some reason the host is blank and the port is
            // zero, the sampler will fail silently
            if (phost.length() > 0 && pport > 0) {
                spconn.setProxyHost(phost);
                spconn.setProxyPort(pport);
                if (PROXY_USER.length() > 0 && PROXY_PASS.length() > 0) {
                    spconn.setProxyUserName(PROXY_USER);
                    spconn.setProxyPassword(PROXY_PASS);
                }
            }
        }
        // by default we maintain the session.
        spconn.setMaintainSession(true);
        msg.setSOAPTransport(spconn);
        msg.send(this.getUrl(), this.getSoapAction(), msgEnv);
        @SuppressWarnings("unchecked") // API uses raw types
        final Map<String, String> headers = spconn.getHeaders();
        result.setResponseHeaders(convertSoapHeaders(headers));

        if (this.getHeaderManager() != null) {
            this.getHeaderManager().setSOAPHeader(spconn);
        }

        BufferedReader br = null;
        if (spconn.receive() != null) {
            br = spconn.receive();
            SOAPContext sc = spconn.getResponseSOAPContext();
            // Set details from the actual response
            // Needs to be done before response can be stored
            final String contentType = sc.getContentType();
            result.setContentType(contentType);
            result.setEncodingAndType(contentType);
            int length = 0;
            if (getReadResponse()) {
                StringWriter sw = new StringWriter();
                length = IOUtils.copy(br, sw);
                result.sampleEnd();
                result.setResponseData(sw.toString().getBytes(result.getDataEncodingWithDefault()));
            } else {
                // by not reading the response
                // for real, it improves the
                // performance on slow clients
                length = br.read();
                result.sampleEnd();
                result.setResponseData(JMeterUtils.getResString("read_response_message"), null); //$NON-NLS-1$
            }
            // It is not possible to access the actual HTTP response code, so we assume no data means failure
            if (length > 0) {
                result.setSuccessful(true);
                result.setResponseCodeOK();
                result.setResponseMessageOK();
            } else {
                result.setSuccessful(false);
                result.setResponseCode("999");
                result.setResponseMessage("Empty response");
            }
        } else {
            result.sampleEnd();
            result.setSuccessful(false);
            final String contentType = spconn.getResponseSOAPContext().getContentType();
            result.setContentType(contentType);
            result.setEncodingAndType(contentType);
            result.setResponseData(
                    spconn.getResponseSOAPContext().toString().getBytes(result.getDataEncodingWithDefault()));
        }
        if (br != null) {
            br.close();
        }
        // reponse code doesn't really apply, since
        // the soap driver doesn't provide a
        // response code
    } catch (IllegalArgumentException exception) {
        String message = exception.getMessage();
        log.warn(message);
        result.setResponseMessage(message);
    } catch (SAXException exception) {
        log.warn(exception.toString());
        result.setResponseMessage(exception.getMessage());
    } catch (SOAPException exception) {
        log.warn(exception.toString());
        result.setResponseMessage(exception.getMessage());
    } catch (MalformedURLException exception) {
        String message = exception.getMessage();
        log.warn(message);
        result.setResponseMessage(message);
    } catch (IOException exception) {
        String message = exception.getMessage();
        log.warn(message);
        result.setResponseMessage(message);
    } catch (NoClassDefFoundError error) {
        log.error("Missing class: ", error);
        result.setResponseMessage(error.toString());
    } catch (Exception exception) {
        if ("javax.mail.MessagingException".equals(exception.getClass().getName())) {
            log.warn(exception.toString());
            result.setResponseMessage(exception.getMessage());
        } else {
            log.error("Problem processing the SOAP request", exception);
            result.setResponseMessage(exception.toString());
        }
    } finally {
        // Make sure the sample start time and sample end time are recorded
        // in order not to confuse the statistics calculation methods: if
        //  an error occurs and an exception is thrown it is possible that
        // the result.sampleStart() or result.sampleEnd() won't be called
        if (result.getStartTime() == 0) {
            result.sampleStart();
        }
        if (result.getEndTime() == 0) {
            result.sampleEnd();
        }
    }
    return result;
}