问:
Calling SSRS 2008 web service from Java
I am trying to implement a Java Spring application that will display SSRS reports. I have been following this tutorial: http://blogs.msdn.com/b/christophputz/archive/2010/05/07/accessing-ms-reporting-services-with-java.aspx. But at a certain point I ran onto a problem.

I downloaded the latest version of Metro wsimport (wsimport version "2.2.8").

I generate the webservices with the following commands:

```<code>wsimport -s -extension src http://devwin/reports/ReportExecution2005.asmx?wsdl
parsing WSDL...
[WARNING] SOAP port "ReportExecutionServiceSoap12": uses a non-standard SOAP 1.2 binding line 1885 of http://devwin/reports/ReportExecution2005.asmx?wsdl
Generating code...
Compiling code...

wsimport -s src -extension http://devwin/reports/ReportService2005.asmx?wsdl
parsing WSDL...
[WARNING] SOAP port "ReportingService2005Soap12": uses a non-standard SOAP 1.2 binding. line 5841 of http://devwin/reports/ReportService2005.asmx?wsdl
Generating code...
Compiling code...
</code>```

I imported the generated source code (/src only because of the bug mentioned in the topic).

I used the following maven dependency

```<code><dependency>
    <groupId>com.sun.xml.ws</groupId>
    <artifactId>jaxws-rt</artifactId>
    <version>2.2.8</version>
</dependency>
</code>```

Here is my class that calls the report:

```<code>import java.util.List;

import javax.xml.ws.BindingProvider;
import javax.xml.ws.Holder;

import com.iphos.rankingcheck.entity.Report;
import com.microsoft.schemas.sqlserver._2005._06._30.reporting.reportingservices.ArrayOfParameterValue;
import com.microsoft.schemas.sqlserver._2005._06._30.reporting.reportingservices.ArrayOfString;
import com.microsoft.schemas.sqlserver._2005._06._30.reporting.reportingservices.ArrayOfWarning;
import com.microsoft.schemas.sqlserver._2005._06._30.reporting.reportingservices.ExecutionHeader;
import com.microsoft.schemas.sqlserver._2005._06._30.reporting.reportingservices.ExecutionInfo;
import com.microsoft.schemas.sqlserver._2005._06._30.reporting.reportingservices.ParameterValue;
import com.microsoft.schemas.sqlserver._2005._06._30.reporting.reportingservices.ReportExecutionService;
import com.microsoft.schemas.sqlserver._2005._06._30.reporting.reportingservices.ReportExecutionServiceSoap;
import com.sun.xml.ws.developer.WSBindingProvider;

public class ReportServiceCaller {
    public static void callReportWS(Report report) {
        String reportPath = "/Path/Report";
        String format = "HTML4.0";
        String historyID = null;
        String devInfo = "<DeviceInfo><Toolbar>False</Toolbar><HTMLFragment>True</HTMLFragment></DeviceInfo>";
        String executionID = null;

        Holder<String> extension = null;
        Holder<String> mimeType = null;
        Holder<String> encoding = null;
        Holder<ArrayOfWarning> warnings = null;
        Holder<ArrayOfString> streamIDs = null;
        Holder<byte[]> result = new Holder<byte[]>();

        ReportExecutionService res = new ReportExecutionService();
        ReportExecutionServiceSoap ress = res.getReportExecutionServiceSoap();

        BindingProvider bp = (BindingProvider)ress;
        WSBindingProvider wsbp = (WSBindingProvider)ress;

        // Sessions erlauben
        bp.getRequestContext().put(BindingProvider.SESSION_MAINTAIN_PROPERTY, true);

        ExecutionInfo execInfo = new ExecutionInfo();

        // Parameterliste erzeugen
        ArrayOfParameterValue apv = new ArrayOfParameterValue();
        List<ParameterValue> apvList = apv.getParameterValue();

        ParameterValue param0 = new ParameterValue();
        param0.setName("Project");
        param0.setValue(report.getProject().getProjectName());
        apvList.add(param0);

        // Report vorbereiten
        execInfo = ress.loadReport(reportPath, historyID);
        // ExecutionID für den nächsten Aufruf merken
        executionID = execInfo.getExecutionID();
        bp.getRequestContext().put("sessionID", executionID);

        // ExecutionHeader Element erzeugen und es für den nächsten Aufruf
        // and den WSBindingProvider übergeben
        ExecutionHeader eh = new ExecutionHeader();
        eh.setExecutionID(executionID);
        wsbp.setOutboundHeaders(eh);

        // Parameter an den Report übergeben
        ress.setExecutionParameters(apv, "en-us");

        // Report anfordern
        ress.render(format, devInfo, result, extension, mimeType, encoding, warnings, streamIDs);
        // Ergebnis des Aufrufs ausgeben
        String resultString = new String(result.value);
    }
}
</code>```

When I try to run the report I get the following exception:

```<code>org.springframework.web.util.NestedServletException: Handler processing failed; nested exception is java.lang.NoSuchMethodError: com.sun.xml.bind.v2.runtime.MarshallerImpl.marshal(Ljava/lang/Object;Ljava/io/OutputStream;Ljavax/xml/namespace/NamespaceContext;)V
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:839)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:669)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:574)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
    org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter.doFilterInternal(OpenEntityManagerInViewFilter.java:113)
    org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
    org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77)
    org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
    org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
    org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
root cause

java.lang.NoSuchMethodError: com.sun.xml.bind.v2.runtime.MarshallerImpl.marshal(Ljava/lang/Object;Ljava/io/OutputStream;Ljavax/xml/namespace/NamespaceContext;)V
    com.sun.xml.ws.db.glassfish.MarshallerBridge.marshal(MarshallerBridge.java:86)
    com.sun.xml.bind.api.Bridge.marshal(Bridge.java:105)
    com.sun.xml.ws.message.jaxb.JAXBHeader.writeTo(JAXBHeader.java:201)
    com.sun.xml.ws.message.AbstractMessageImpl.writeTo(AbstractMessageImpl.java:148)
    com.sun.xml.ws.api.message.MessageWrapper.writeTo(MessageWrapper.java:230)
    com.sun.xml.ws.encoding.StreamSOAPCodec.encode(StreamSOAPCodec.java:134)
    com.sun.xml.ws.encoding.SOAPBindingCodec.encode(SOAPBindingCodec.java:242)
    com.sun.xml.ws.transport.http.client.HttpTransportPipe.process(HttpTransportPipe.java:223)
    com.sun.xml.ws.transport.http.client.HttpTransportPipe.processRequest(HttpTransportPipe.java:143)
    com.sun.xml.ws.transport.DeferredTransportPipe.processRequest(DeferredTransportPipe.java:110)
    com.sun.xml.ws.api.pipe.Fiber.__doRun(Fiber.java:1136)
    com.sun.xml.ws.api.pipe.Fiber._doRun(Fiber.java:1050)
    com.sun.xml.ws.api.pipe.Fiber.doRun(Fiber.java:1019)
    com.sun.xml.ws.api.pipe.Fiber.runSync(Fiber.java:877)
    com.sun.xml.ws.client.Stub.process(Stub.java:464)
    com.sun.xml.ws.client.sei.SEIStub.doProcess(SEIStub.java:174)
    com.sun.xml.ws.client.sei.SyncMethodHandler.invoke(SyncMethodHandler.java:108)
    com.sun.xml.ws.client.sei.SyncMethodHandler.invoke(SyncMethodHandler.java:91)
    com.sun.xml.ws.client.sei.SEIStub.invoke(SEIStub.java:154)
    com.sun.proxy.$Proxy93.setExecutionParameters(Unknown Source)
    com.iphos.rankingcheck.util.ReportServiceCaller.callReportWS(ReportServiceCaller.java:79)
    com.iphos.rankingcheck.controller.ReportController.display(ReportController.java:209)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    java.lang.reflect.Method.invoke(Method.java:601)
    org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:176)
    org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:436)
    org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:424)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:790)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:669)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:574)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
    org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter.doFilterInternal(OpenEntityManagerInViewFilter.java:113)
    org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
    org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77)
    org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
    org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
    org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
</code>```

I figured out that probably the implementation of that method is missing so I tried to search for a dependency to provide it. I found a few, but I was able to move from that exception only with that one:

```<code><dependency>
    <groupId>com.sun.xml.bind</groupId>
    <artifactId>jaxb-impl</artifactId>
    <version>2.2.7</version>
</dependency>
</code>```

When I added it I got the following exception:

```<code>org.springframework.web.util.NestedServletException: Request processing failed; nested exception is javax.xml.ws.WebServiceException: com.sun.istack.XMLStreamException2: javax.xml.bind.JAXBException: class com.microsoft.schemas.sqlserver._2005._06._30.reporting.reportingservices.ExecutionHeader nor any of its super class is known to this context.
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:681)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:574)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
    org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter.doFilterInternal(OpenEntityManagerInViewFilter.java:113)
    org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
    org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77)
    org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
    org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
    org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
root cause

javax.xml.ws.WebServiceException: com.sun.istack.XMLStreamException2: javax.xml.bind.JAXBException: class com.microsoft.schemas.sqlserver._2005._06._30.reporting.reportingservices.ExecutionHeader nor any of its super class is known to this context.
    com.sun.xml.ws.encoding.StreamSOAPCodec.encode(StreamSOAPCodec.java:137)
    com.sun.xml.ws.encoding.SOAPBindingCodec.encode(SOAPBindingCodec.java:242)
    com.sun.xml.ws.transport.http.client.HttpTransportPipe.process(HttpTransportPipe.java:223)
    com.sun.xml.ws.transport.http.client.HttpTransportPipe.processRequest(HttpTransportPipe.java:143)
    com.sun.xml.ws.transport.DeferredTransportPipe.processRequest(DeferredTransportPipe.java:110)
    com.sun.xml.ws.api.pipe.Fiber.__doRun(Fiber.java:1136)
    com.sun.xml.ws.api.pipe.Fiber._doRun(Fiber.java:1050)
    com.sun.xml.ws.api.pipe.Fiber.doRun(Fiber.java:1019)
    com.sun.xml.ws.api.pipe.Fiber.runSync(Fiber.java:877)
    com.sun.xml.ws.client.Stub.process(Stub.java:464)
    com.sun.xml.ws.client.sei.SEIStub.doProcess(SEIStub.java:174)
    com.sun.xml.ws.client.sei.SyncMethodHandler.invoke(SyncMethodHandler.java:108)
    com.sun.xml.ws.client.sei.SyncMethodHandler.invoke(SyncMethodHandler.java:91)
    com.sun.xml.ws.client.sei.SEIStub.invoke(SEIStub.java:154)
    com.sun.proxy.$Proxy93.setExecutionParameters(Unknown Source)
    com.iphos.rankingcheck.util.ReportServiceCaller.callReportWS(ReportServiceCaller.java:79)
    com.iphos.rankingcheck.controller.ReportController.display(ReportController.java:209)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    java.lang.reflect.Method.invoke(Method.java:601)
    org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:176)
    org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:436)
    org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:424)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:790)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:669)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:574)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
    org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter.doFilterInternal(OpenEntityManagerInViewFilter.java:113)
    org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
    org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77)
    org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
    org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
    org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
root cause

com.sun.istack.XMLStreamException2: javax.xml.bind.JAXBException: class com.microsoft.schemas.sqlserver._2005._06._30.reporting.reportingservices.ExecutionHeader nor any of its super class is known to this context.
    com.sun.xml.ws.message.jaxb.JAXBHeader.writeTo(JAXBHeader.java:206)
    com.sun.xml.ws.message.AbstractMessageImpl.writeTo(AbstractMessageImpl.java:148)
    com.sun.xml.ws.api.message.MessageWrapper.writeTo(MessageWrapper.java:230)
    com.sun.xml.ws.encoding.StreamSOAPCodec.encode(StreamSOAPCodec.java:134)
    com.sun.xml.ws.encoding.SOAPBindingCodec.encode(SOAPBindingCodec.java:242)
    com.sun.xml.ws.transport.http.client.HttpTransportPipe.process(HttpTransportPipe.java:223)
    com.sun.xml.ws.transport.http.client.HttpTransportPipe.processRequest(HttpTransportPipe.java:143)
    com.sun.xml.ws.transport.DeferredTransportPipe.processRequest(DeferredTransportPipe.java:110)
    com.sun.xml.ws.api.pipe.Fiber.__doRun(Fiber.java:1136)
    com.sun.xml.ws.api.pipe.Fiber._doRun(Fiber.java:1050)
    com.sun.xml.ws.api.pipe.Fiber.doRun(Fiber.java:1019)
    com.sun.xml.ws.api.pipe.Fiber.runSync(Fiber.java:877)
    com.sun.xml.ws.client.Stub.process(Stub.java:464)
    com.sun.xml.ws.client.sei.SEIStub.doProcess(SEIStub.java:174)
    com.sun.xml.ws.client.sei.SyncMethodHandler.invoke(SyncMethodHandler.java:108)
    com.sun.xml.ws.client.sei.SyncMethodHandler.invoke(SyncMethodHandler.java:91)
    com.sun.xml.ws.client.sei.SEIStub.invoke(SEIStub.java:154)
    com.sun.proxy.$Proxy93.setExecutionParameters(Unknown Source)
    com.iphos.rankingcheck.util.ReportServiceCaller.callReportWS(ReportServiceCaller.java:79)
    com.iphos.rankingcheck.controller.ReportController.display(ReportController.java:209)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    java.lang.reflect.Method.invoke(Method.java:601)
    org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:176)
    org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:436)
    org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:424)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:790)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:669)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:574)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
    org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter.doFilterInternal(OpenEntityManagerInViewFilter.java:113)
    org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
    org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77)
    org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
    org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
    org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
root cause

javax.xml.bind.JAXBException: class com.microsoft.schemas.sqlserver._2005._06._30.reporting.reportingservices.ExecutionHeader nor any of its super class is known to this context.
    com.sun.xml.bind.v2.runtime.JAXBContextImpl.getBeanInfo(JAXBContextImpl.java:593)
    com.sun.xml.bind.v2.runtime.XMLSerializer.childAsRoot(XMLSerializer.java:482)
    com.sun.xml.bind.v2.runtime.MarshallerImpl.write(MarshallerImpl.java:323)
    com.sun.xml.bind.v2.runtime.MarshallerImpl.marshal(MarshallerImpl.java:173)
    com.sun.xml.ws.db.glassfish.MarshallerBridge.marshal(MarshallerBridge.java:86)
    com.sun.xml.bind.api.Bridge.marshal(Bridge.java:145)
    com.sun.xml.ws.message.jaxb.JAXBHeader.writeTo(JAXBHeader.java:201)
    com.sun.xml.ws.message.AbstractMessageImpl.writeTo(AbstractMessageImpl.java:148)
    com.sun.xml.ws.api.message.MessageWrapper.writeTo(MessageWrapper.java:230)
    com.sun.xml.ws.encoding.StreamSOAPCodec.encode(StreamSOAPCodec.java:134)
    com.sun.xml.ws.encoding.SOAPBindingCodec.encode(SOAPBindingCodec.java:242)
    com.sun.xml.ws.transport.http.client.HttpTransportPipe.process(HttpTransportPipe.java:223)
    com.sun.xml.ws.transport.http.client.HttpTransportPipe.processRequest(HttpTransportPipe.java:143)
    com.sun.xml.ws.transport.DeferredTransportPipe.processRequest(DeferredTransportPipe.java:110)
    com.sun.xml.ws.api.pipe.Fiber.__doRun(Fiber.java:1136)
    com.sun.xml.ws.api.pipe.Fiber._doRun(Fiber.java:1050)
    com.sun.xml.ws.api.pipe.Fiber.doRun(Fiber.java:1019)
    com.sun.xml.ws.api.pipe.Fiber.runSync(Fiber.java:877)
    com.sun.xml.ws.client.Stub.process(Stub.java:464)
    com.sun.xml.ws.client.sei.SEIStub.doProcess(SEIStub.java:174)
    com.sun.xml.ws.client.sei.SyncMethodHandler.invoke(SyncMethodHandler.java:108)
    com.sun.xml.ws.client.sei.SyncMethodHandler.invoke(SyncMethodHandler.java:91)
    com.sun.xml.ws.client.sei.SEIStub.invoke(SEIStub.java:154)
    com.sun.proxy.$Proxy93.setExecutionParameters(Unknown Source)
    com.iphos.rankingcheck.util.ReportServiceCaller.callReportWS(ReportServiceCaller.java:79)
    com.iphos.rankingcheck.controller.ReportController.display(ReportController.java:209)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    java.lang.reflect.Method.invoke(Method.java:601)
    org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:176)
    org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:436)
    org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:424)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:790)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:669)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:574)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
    org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter.doFilterInternal(OpenEntityManagerInViewFilter.java:113)
    org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
    org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77)
    org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
    org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
    org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
</code>```

I tried adding other dependencies like: webservices-rt, webservices-osgi and others, but I was unable to resolve the issue.

Any suggestions would be apprecieated.

答:
Here is solution using axis.

build.gradle

```<code>dependencies {
    compile('commons-discovery:commons-discovery:0.5')
    compile('org.apache.axis:axis:1.4')
    compile('org.apache.axis:axis-jaxrpc:1.4')
    compile('org.apache.axis:axis-saaj:1.4')
    compile('axis:axis-wsdl4j:1.5.1')

    axisGenAntTask 'org.apache.axis:axis-ant:1.4',
        'org.apache.axis:axis:1.4',
        'org.apache.axis:axis-jaxrpc:1.4',
        'axis:axis-wsdl4j:1.5.1',
        'commons-codec:commons-codec:1.3',
        'commons-logging:commons-logging:1.1.1',
        'commons-discovery:commons-discovery:0.2'
}

task genWsdlClasses {
    doLast {
        def destDir = file("${buildDir}/generated/src/main/java")

        ant.taskdef(name: 'genClassesFromWSDL',
                    classname: 'org.apache.axis.tools.ant.wsdl.Wsdl2javaAntTask',
                    classpath: configurations.axisGenAntTask.asPath)

        destDir.mkdirs()

        ant.genClassesFromWSDL(url: "pathOrUrlToWsdl", output: destDir, username: "optionalUsername", password: "optionalPwd");
    }
}

sourceSets {
    generated {
        java.srcDirs "${buildDir}/generated/src/main/java"
    }

    main {
        compileClasspath += generated.output
        runtimeClasspath += generated.output
    }

    test {
        compileClasspath += generated.output
        runtimeClasspath += generated.output
    }
}

compileGeneratedJava {
    dependsOn(genWsdlClasses)
    classpath = configurations.compile
}

compileJava{
    dependsOn(compileGeneratedJava)
    source += sourceSets.generated.java
}
</code>```

java code

```<code>public String getHtml(String reportPath, Map<String, String> reportParameters) {
        try {
            ReportExecutionService reportExecution = new ReportExecutionServiceLocator();
            ReportExecutionServiceSoapStub ress = (ReportExecutionServiceSoapStub) reportExecution.getReportExecutionServiceSoap();

            final ExecutionInfo info = ress.loadReport(reportPath, null);
            final String executionId = info.getExecutionID();

            SOAPHeaderElement sessionHeader = new SOAPHeaderElement(
                    "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices",
                    "ExecutionHeader");
            SOAPElement addChildElement = sessionHeader.addChildElement("ExecutionID");
            addChildElement.addTextNode(executionId);
            ress.setHeader(sessionHeader);

            final ParameterValue[] parameters = new ParameterValue[reportParameters != null ? reportParameters.size() : 0];
            if (reportParameters != null && !reportParameters.isEmpty()) {
                int i = 0;
                for (final String name : reportParameters.keySet()) {
                    final String value = reportParameters.get(name);
                    ParameterValue parameterValue = new ParameterValue();
                    parameterValue.setName(name);
                    parameterValue.setValue(value);

                    parameters[i++] = parameterValue;
                }
            }
            ress.setExecutionParameters(parameters, "en-us");

            String format = "HTML4.0";
            String devInfo = "<DeviceInfo><Toolbar>False</Toolbar><HTMLFragment>True</HTMLFragment></DeviceInfo>";
            final ByteArrayHolder result = new ByteArrayHolder();
            final StringHolder extension = new StringHolder();
            final StringHolder mimeType = new StringHolder("text/html");
            final StringHolder encoding = new StringHolder(StandardCharsets.UTF_8.name());
            final ArrayOfWarningHolder warnings = new ArrayOfWarningHolder();
            final ArrayOfStringHolder streamIds = new ArrayOfStringHolder();

            ress.render(format, devInfo, result, extension, mimeType, encoding, warnings, streamIds);

            return new String(result.value);
        } catch (Exception e) {
            throw new RuntimeException("Report generation error", e);
        }
    }
</code>```

Title: Calling SSRS 2008 web service from Java

Body:
I am trying to implement a Java Spring application that will display SSRS reports. I have been following this tutorial: http://blogs.msdn.com/b/christophputz/archive/2010/05/07/accessing-ms-reporting-services-with-java.aspx. But at a certain point I ran onto a problem.

I downloaded the latest version of Metro wsimport (wsimport version "2.2.8").

I generate the webservices with the following commands:

wsimport -s -extension src http://devwin/reports/ReportExecution2005.asmx?wsdl
parsing WSDL...
[WARNING] SOAP port "ReportExecutionServiceSoap12": uses a non-standard SOAP 1.2 binding line 1885 of http://devwin/reports/ReportExecution2005.asmx?wsdl
Generating code...
Compiling code...

wsimport -s src -extension http://devwin/reports/ReportService2005.asmx?wsdl
parsing WSDL...
[WARNING] SOAP port "ReportingService2005Soap12": uses a non-standard SOAP 1.2 binding. line 5841 of http://devwin/reports/ReportService2005.asmx?wsdl
Generating code...
Compiling code...

I imported the generated source code (/src only because of the bug mentioned in the topic).

I used the following maven dependency

<dependency>
    <groupId>com.sun.xml.ws</groupId>
    <artifactId>jaxws-rt</artifactId>
    <version>2.2.8</version>
</dependency>

Here is my class that calls the report:

import java.util.List;

import javax.xml.ws.BindingProvider;
import javax.xml.ws.Holder;

import com.iphos.rankingcheck.entity.Report;
import com.microsoft.schemas.sqlserver._2005._06._30.reporting.reportingservices.ArrayOfParameterValue;
import com.microsoft.schemas.sqlserver._2005._06._30.reporting.reportingservices.ArrayOfString;
import com.microsoft.schemas.sqlserver._2005._06._30.reporting.reportingservices.ArrayOfWarning;
import com.microsoft.schemas.sqlserver._2005._06._30.reporting.reportingservices.ExecutionHeader;
import com.microsoft.schemas.sqlserver._2005._06._30.reporting.reportingservices.ExecutionInfo;
import com.microsoft.schemas.sqlserver._2005._06._30.reporting.reportingservices.ParameterValue;
import com.microsoft.schemas.sqlserver._2005._06._30.reporting.reportingservices.ReportExecutionService;
import com.microsoft.schemas.sqlserver._2005._06._30.reporting.reportingservices.ReportExecutionServiceSoap;
import com.sun.xml.ws.developer.WSBindingProvider;

public class ReportServiceCaller {
    public static void callReportWS(Report report) {
        String reportPath = "/Path/Report";
        String format = "HTML4.0";
        String historyID = null;
        String devInfo = "<DeviceInfo><Toolbar>False</Toolbar><HTMLFragment>True</HTMLFragment></DeviceInfo>";
        String executionID = null;

        Holder<String> extension = null;
        Holder<String> mimeType = null;
        Holder<String> encoding = null;
        Holder<ArrayOfWarning> warnings = null;
        Holder<ArrayOfString> streamIDs = null;
        Holder<byte[]> result = new Holder<byte[]>();

        ReportExecutionService res = new ReportExecutionService();
        ReportExecutionServiceSoap ress = res.getReportExecutionServiceSoap();

        BindingProvider bp = (BindingProvider)ress;
        WSBindingProvider wsbp = (WSBindingProvider)ress;

        // Sessions erlauben
        bp.getRequestContext().put(BindingProvider.SESSION_MAINTAIN_PROPERTY, true);

        ExecutionInfo execInfo = new ExecutionInfo();

        // Parameterliste erzeugen
        ArrayOfParameterValue apv = new ArrayOfParameterValue();
        List<ParameterValue> apvList = apv.getParameterValue();

        ParameterValue param0 = new ParameterValue();
        param0.setName("Project");
        param0.setValue(report.getProject().getProjectName());
        apvList.add(param0);

        // Report vorbereiten
        execInfo = ress.loadReport(reportPath, historyID);
        // ExecutionID für den nächsten Aufruf merken
        executionID = execInfo.getExecutionID();
        bp.getRequestContext().put("sessionID", executionID);

        // ExecutionHeader Element erzeugen und es für den nächsten Aufruf
        // and den WSBindingProvider übergeben
        ExecutionHeader eh = new ExecutionHeader();
        eh.setExecutionID(executionID);
        wsbp.setOutboundHeaders(eh);

        // Parameter an den Report übergeben
        ress.setExecutionParameters(apv, "en-us");

        // Report anfordern
        ress.render(format, devInfo, result, extension, mimeType, encoding, warnings, streamIDs);
        // Ergebnis des Aufrufs ausgeben
        String resultString = new String(result.value);
    }
}

When I try to run the report I get the following exception:

org.springframework.web.util.NestedServletException: Handler processing failed; nested exception is java.lang.NoSuchMethodError: com.sun.xml.bind.v2.runtime.MarshallerImpl.marshal(Ljava/lang/Object;Ljava/io/OutputStream;Ljavax/xml/namespace/NamespaceContext;)V
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:839)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:669)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:574)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
    org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter.doFilterInternal(OpenEntityManagerInViewFilter.java:113)
    org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
    org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77)
    org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
    org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
    org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
root cause

java.lang.NoSuchMethodError: com.sun.xml.bind.v2.runtime.MarshallerImpl.marshal(Ljava/lang/Object;Ljava/io/OutputStream;Ljavax/xml/namespace/NamespaceContext;)V
    com.sun.xml.ws.db.glassfish.MarshallerBridge.marshal(MarshallerBridge.java:86)
    com.sun.xml.bind.api.Bridge.marshal(Bridge.java:105)
    com.sun.xml.ws.message.jaxb.JAXBHeader.writeTo(JAXBHeader.java:201)
    com.sun.xml.ws.message.AbstractMessageImpl.writeTo(AbstractMessageImpl.java:148)
    com.sun.xml.ws.api.message.MessageWrapper.writeTo(MessageWrapper.java:230)
    com.sun.xml.ws.encoding.StreamSOAPCodec.encode(StreamSOAPCodec.java:134)
    com.sun.xml.ws.encoding.SOAPBindingCodec.encode(SOAPBindingCodec.java:242)
    com.sun.xml.ws.transport.http.client.HttpTransportPipe.process(HttpTransportPipe.java:223)
    com.sun.xml.ws.transport.http.client.HttpTransportPipe.processRequest(HttpTransportPipe.java:143)
    com.sun.xml.ws.transport.DeferredTransportPipe.processRequest(DeferredTransportPipe.java:110)
    com.sun.xml.ws.api.pipe.Fiber.__doRun(Fiber.java:1136)
    com.sun.xml.ws.api.pipe.Fiber._doRun(Fiber.java:1050)
    com.sun.xml.ws.api.pipe.Fiber.doRun(Fiber.java:1019)
    com.sun.xml.ws.api.pipe.Fiber.runSync(Fiber.java:877)
    com.sun.xml.ws.client.Stub.process(Stub.java:464)
    com.sun.xml.ws.client.sei.SEIStub.doProcess(SEIStub.java:174)
    com.sun.xml.ws.client.sei.SyncMethodHandler.invoke(SyncMethodHandler.java:108)
    com.sun.xml.ws.client.sei.SyncMethodHandler.invoke(SyncMethodHandler.java:91)
    com.sun.xml.ws.client.sei.SEIStub.invoke(SEIStub.java:154)
    com.sun.proxy.$Proxy93.setExecutionParameters(Unknown Source)
    com.iphos.rankingcheck.util.ReportServiceCaller.callReportWS(ReportServiceCaller.java:79)
    com.iphos.rankingcheck.controller.ReportController.display(ReportController.java:209)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    java.lang.reflect.Method.invoke(Method.java:601)
    org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:176)
    org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:436)
    org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:424)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:790)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:669)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:574)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
    org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter.doFilterInternal(OpenEntityManagerInViewFilter.java:113)
    org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
    org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77)
    org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
    org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
    org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)

I figured out that probably the implementation of that method is missing so I tried to search for a dependency to provide it. I found a few, but I was able to move from that exception only with that one:

<dependency>
    <groupId>com.sun.xml.bind</groupId>
    <artifactId>jaxb-impl</artifactId>
    <version>2.2.7</version>
</dependency>

When I added it I got the following exception:

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is javax.xml.ws.WebServiceException: com.sun.istack.XMLStreamException2: javax.xml.bind.JAXBException: class com.microsoft.schemas.sqlserver._2005._06._30.reporting.reportingservices.ExecutionHeader nor any of its super class is known to this context.
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:681)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:574)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
    org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter.doFilterInternal(OpenEntityManagerInViewFilter.java:113)
    org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
    org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77)
    org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
    org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
    org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
root cause

javax.xml.ws.WebServiceException: com.sun.istack.XMLStreamException2: javax.xml.bind.JAXBException: class com.microsoft.schemas.sqlserver._2005._06._30.reporting.reportingservices.ExecutionHeader nor any of its super class is known to this context.
    com.sun.xml.ws.encoding.StreamSOAPCodec.encode(StreamSOAPCodec.java:137)
    com.sun.xml.ws.encoding.SOAPBindingCodec.encode(SOAPBindingCodec.java:242)
    com.sun.xml.ws.transport.http.client.HttpTransportPipe.process(HttpTransportPipe.java:223)
    com.sun.xml.ws.transport.http.client.HttpTransportPipe.processRequest(HttpTransportPipe.java:143)
    com.sun.xml.ws.transport.DeferredTransportPipe.processRequest(DeferredTransportPipe.java:110)
    com.sun.xml.ws.api.pipe.Fiber.__doRun(Fiber.java:1136)
    com.sun.xml.ws.api.pipe.Fiber._doRun(Fiber.java:1050)
    com.sun.xml.ws.api.pipe.Fiber.doRun(Fiber.java:1019)
    com.sun.xml.ws.api.pipe.Fiber.runSync(Fiber.java:877)
    com.sun.xml.ws.client.Stub.process(Stub.java:464)
    com.sun.xml.ws.client.sei.SEIStub.doProcess(SEIStub.java:174)
    com.sun.xml.ws.client.sei.SyncMethodHandler.invoke(SyncMethodHandler.java:108)
    com.sun.xml.ws.client.sei.SyncMethodHandler.invoke(SyncMethodHandler.java:91)
    com.sun.xml.ws.client.sei.SEIStub.invoke(SEIStub.java:154)
    com.sun.proxy.$Proxy93.setExecutionParameters(Unknown Source)
    com.iphos.rankingcheck.util.ReportServiceCaller.callReportWS(ReportServiceCaller.java:79)
    com.iphos.rankingcheck.controller.ReportController.display(ReportController.java:209)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    java.lang.reflect.Method.invoke(Method.java:601)
    org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:176)
    org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:436)
    org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:424)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:790)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:669)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:574)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
    org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter.doFilterInternal(OpenEntityManagerInViewFilter.java:113)
    org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
    org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77)
    org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
    org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
    org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
root cause

com.sun.istack.XMLStreamException2: javax.xml.bind.JAXBException: class com.microsoft.schemas.sqlserver._2005._06._30.reporting.reportingservices.ExecutionHeader nor any of its super class is known to this context.
    com.sun.xml.ws.message.jaxb.JAXBHeader.writeTo(JAXBHeader.java:206)
    com.sun.xml.ws.message.AbstractMessageImpl.writeTo(AbstractMessageImpl.java:148)
    com.sun.xml.ws.api.message.MessageWrapper.writeTo(MessageWrapper.java:230)
    com.sun.xml.ws.encoding.StreamSOAPCodec.encode(StreamSOAPCodec.java:134)
    com.sun.xml.ws.encoding.SOAPBindingCodec.encode(SOAPBindingCodec.java:242)
    com.sun.xml.ws.transport.http.client.HttpTransportPipe.process(HttpTransportPipe.java:223)
    com.sun.xml.ws.transport.http.client.HttpTransportPipe.processRequest(HttpTransportPipe.java:143)
    com.sun.xml.ws.transport.DeferredTransportPipe.processRequest(DeferredTransportPipe.java:110)
    com.sun.xml.ws.api.pipe.Fiber.__doRun(Fiber.java:1136)
    com.sun.xml.ws.api.pipe.Fiber._doRun(Fiber.java:1050)
    com.sun.xml.ws.api.pipe.Fiber.doRun(Fiber.java:1019)
    com.sun.xml.ws.api.pipe.Fiber.runSync(Fiber.java:877)
    com.sun.xml.ws.client.Stub.process(Stub.java:464)
    com.sun.xml.ws.client.sei.SEIStub.doProcess(SEIStub.java:174)
    com.sun.xml.ws.client.sei.SyncMethodHandler.invoke(SyncMethodHandler.java:108)
    com.sun.xml.ws.client.sei.SyncMethodHandler.invoke(SyncMethodHandler.java:91)
    com.sun.xml.ws.client.sei.SEIStub.invoke(SEIStub.java:154)
    com.sun.proxy.$Proxy93.setExecutionParameters(Unknown Source)
    com.iphos.rankingcheck.util.ReportServiceCaller.callReportWS(ReportServiceCaller.java:79)
    com.iphos.rankingcheck.controller.ReportController.display(ReportController.java:209)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    java.lang.reflect.Method.invoke(Method.java:601)
    org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:176)
    org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:436)
    org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:424)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:790)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:669)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:574)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
    org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter.doFilterInternal(OpenEntityManagerInViewFilter.java:113)
    org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
    org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77)
    org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
    org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
    org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
root cause

javax.xml.bind.JAXBException: class com.microsoft.schemas.sqlserver._2005._06._30.reporting.reportingservices.ExecutionHeader nor any of its super class is known to this context.
    com.sun.xml.bind.v2.runtime.JAXBContextImpl.getBeanInfo(JAXBContextImpl.java:593)
    com.sun.xml.bind.v2.runtime.XMLSerializer.childAsRoot(XMLSerializer.java:482)
    com.sun.xml.bind.v2.runtime.MarshallerImpl.write(MarshallerImpl.java:323)
    com.sun.xml.bind.v2.runtime.MarshallerImpl.marshal(MarshallerImpl.java:173)
    com.sun.xml.ws.db.glassfish.MarshallerBridge.marshal(MarshallerBridge.java:86)
    com.sun.xml.bind.api.Bridge.marshal(Bridge.java:145)
    com.sun.xml.ws.message.jaxb.JAXBHeader.writeTo(JAXBHeader.java:201)
    com.sun.xml.ws.message.AbstractMessageImpl.writeTo(AbstractMessageImpl.java:148)
    com.sun.xml.ws.api.message.MessageWrapper.writeTo(MessageWrapper.java:230)
    com.sun.xml.ws.encoding.StreamSOAPCodec.encode(StreamSOAPCodec.java:134)
    com.sun.xml.ws.encoding.SOAPBindingCodec.encode(SOAPBindingCodec.java:242)
    com.sun.xml.ws.transport.http.client.HttpTransportPipe.process(HttpTransportPipe.java:223)
    com.sun.xml.ws.transport.http.client.HttpTransportPipe.processRequest(HttpTransportPipe.java:143)
    com.sun.xml.ws.transport.DeferredTransportPipe.processRequest(DeferredTransportPipe.java:110)
    com.sun.xml.ws.api.pipe.Fiber.__doRun(Fiber.java:1136)
    com.sun.xml.ws.api.pipe.Fiber._doRun(Fiber.java:1050)
    com.sun.xml.ws.api.pipe.Fiber.doRun(Fiber.java:1019)
    com.sun.xml.ws.api.pipe.Fiber.runSync(Fiber.java:877)
    com.sun.xml.ws.client.Stub.process(Stub.java:464)
    com.sun.xml.ws.client.sei.SEIStub.doProcess(SEIStub.java:174)
    com.sun.xml.ws.client.sei.SyncMethodHandler.invoke(SyncMethodHandler.java:108)
    com.sun.xml.ws.client.sei.SyncMethodHandler.invoke(SyncMethodHandler.java:91)
    com.sun.xml.ws.client.sei.SEIStub.invoke(SEIStub.java:154)
    com.sun.proxy.$Proxy93.setExecutionParameters(Unknown Source)
    com.iphos.rankingcheck.util.ReportServiceCaller.callReportWS(ReportServiceCaller.java:79)
    com.iphos.rankingcheck.controller.ReportController.display(ReportController.java:209)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    java.lang.reflect.Method.invoke(Method.java:601)
    org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:176)
    org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:436)
    org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:424)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:790)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:669)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:574)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
    org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter.doFilterInternal(OpenEntityManagerInViewFilter.java:113)
    org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
    org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77)
    org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
    org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
    org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)

I tried adding other dependencies like: webservices-rt, webservices-osgi and others, but I was unable to resolve the issue.

Any suggestions would be apprecieated.

Body:
Here is solution using axis.

build.gradle

dependencies {
    compile('commons-discovery:commons-discovery:0.5')
    compile('org.apache.axis:axis:1.4')
    compile('org.apache.axis:axis-jaxrpc:1.4')
    compile('org.apache.axis:axis-saaj:1.4')
    compile('axis:axis-wsdl4j:1.5.1')

    axisGenAntTask 'org.apache.axis:axis-ant:1.4',
        'org.apache.axis:axis:1.4',
        'org.apache.axis:axis-jaxrpc:1.4',
        'axis:axis-wsdl4j:1.5.1',
        'commons-codec:commons-codec:1.3',
        'commons-logging:commons-logging:1.1.1',
        'commons-discovery:commons-discovery:0.2'
}

task genWsdlClasses {
    doLast {
        def destDir = file("${buildDir}/generated/src/main/java")

        ant.taskdef(name: 'genClassesFromWSDL',
                    classname: 'org.apache.axis.tools.ant.wsdl.Wsdl2javaAntTask',
                    classpath: configurations.axisGenAntTask.asPath)

        destDir.mkdirs()

        ant.genClassesFromWSDL(url: "pathOrUrlToWsdl", output: destDir, username: "optionalUsername", password: "optionalPwd");
    }
}

sourceSets {
    generated {
        java.srcDirs "${buildDir}/generated/src/main/java"
    }

    main {
        compileClasspath += generated.output
        runtimeClasspath += generated.output
    }

    test {
        compileClasspath += generated.output
        runtimeClasspath += generated.output
    }
}

compileGeneratedJava {
    dependsOn(genWsdlClasses)
    classpath = configurations.compile
}

compileJava{
    dependsOn(compileGeneratedJava)
    source += sourceSets.generated.java
}

java code

public String getHtml(String reportPath, Map<String, String> reportParameters) {
        try {
            ReportExecutionService reportExecution = new ReportExecutionServiceLocator();
            ReportExecutionServiceSoapStub ress = (ReportExecutionServiceSoapStub) reportExecution.getReportExecutionServiceSoap();

            final ExecutionInfo info = ress.loadReport(reportPath, null);
            final String executionId = info.getExecutionID();

            SOAPHeaderElement sessionHeader = new SOAPHeaderElement(
                    "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices",
                    "ExecutionHeader");
            SOAPElement addChildElement = sessionHeader.addChildElement("ExecutionID");
            addChildElement.addTextNode(executionId);
            ress.setHeader(sessionHeader);

            final ParameterValue[] parameters = new ParameterValue[reportParameters != null ? reportParameters.size() : 0];
            if (reportParameters != null && !reportParameters.isEmpty()) {
                int i = 0;
                for (final String name : reportParameters.keySet()) {
                    final String value = reportParameters.get(name);
                    ParameterValue parameterValue = new ParameterValue();
                    parameterValue.setName(name);
                    parameterValue.setValue(value);

                    parameters[i++] = parameterValue;
                }
            }
            ress.setExecutionParameters(parameters, "en-us");

            String format = "HTML4.0";
            String devInfo = "<DeviceInfo><Toolbar>False</Toolbar><HTMLFragment>True</HTMLFragment></DeviceInfo>";
            final ByteArrayHolder result = new ByteArrayHolder();
            final StringHolder extension = new StringHolder();
            final StringHolder mimeType = new StringHolder("text/html");
            final StringHolder encoding = new StringHolder(StandardCharsets.UTF_8.name());
            final ArrayOfWarningHolder warnings = new ArrayOfWarningHolder();
            final ArrayOfStringHolder streamIds = new ArrayOfStringHolder();

            ress.render(format, devInfo, result, extension, mimeType, encoding, warnings, streamIds);

            return new String(result.value);
        } catch (Exception e) {
            throw new RuntimeException("Report generation error", e);
        }
    }


来源: stackexchange

问:
strip remove '_' unexpectedly
```<code>>>> x = 'abc_cde_fgh'
>>> x.strip('abc_cde')
'fgh'
</code>```

_fgh is expected.

How to understard this result?

答: In the documentation of the strip method "The chars argument is a string specifying the set of characters to be removed."  That is why every chars except "fgh" are removed (including the two underscores).</p>

ContentLicense: CC BY-SA 3.0

Title: strip remove '_' unexpectedly

Body:
>>> x = 'abc_cde_fgh'
>>> x.strip('abc_cde')
'fgh'

_fgh is expected.

How to understard this result?


问:
How to remove extra comma when concatenating strings
```<code>$folders = Get-ChildItem | where {$_.Attributes -match 'Directory'}
foreach ($items in $folders)
{
$type = $items.name
$cat = $cat + "," + "$type/*.$type
}
$cat
</code>```

This is supposed to print text, text but instead it adds an extra comma I understand due to how the script is written it will cause it to add the extra comma. I am trying to figure out if there is another way to write this that removes the extra comma.

This is written with concatenation because of off the top of my head it seemed simpler because everything is under one variable and what is being passed to works well in this situation.

答:
Give this a try:

```<code>$cat = (Get-ChildItem | where {$_.Attributes -match 'Directory'}).Name -join ","
</code>```

EDIT

I'm trying to understand the comment and question edit. Maybe this is what you want?

```<code>(gci -dir) | select {"$($_.Name)/*.$($_.Name)"}
</code>```

EDIT 2

I'm not good at PowerShell, but putting it all together, at least this seems to work:

```<code>$cat = ((gci -dir -name) | select @{Name="Item";Expression={"$($_)/*.$($_)"}}).Item -join ","
</code>```

EDIT 3

This is finally starting to look like a good solution:

```<code>$cat = ((gci -dir -name) | foreach {"$($_)/*.$($_)"}) -join ","
</code>```

Body:
$folders = Get-ChildItem | where {$_.Attributes -match 'Directory'}
foreach ($items in $folders)
{
$type = $items.name
$cat = $cat + "," + "$type/*.$type
}
$cat

This is supposed to print text, text but instead it adds an extra comma I understand due to how the script is written it will cause it to add the extra comma. I am trying to figure out if there is another way to write this that removes the extra comma.

This is written with concatenation because of off the top of my head it seemed simpler because everything is under one variable and what is being passed to works well in this situation.

Body:
Give this a try:

$cat = (Get-ChildItem | where {$_.Attributes -match 'Directory'}).Name -join ","

EDIT

I'm trying to understand the comment and question edit. Maybe this is what you want?

(gci -dir) | select {"$($_.Name)/*.$($_.Name)"}

EDIT 2

I'm not good at PowerShell, but putting it all together, at least this seems to work:

$cat = ((gci -dir -name) | select @{Name="Item";Expression={"$($_)/*.$($_)"}}).Item -join ","

EDIT 3

This is finally starting to look like a good solution:

$cat = ((gci -dir -name) | foreach {"$($_)/*.$($_)"}) -join ","


问:
At Least Once Delivery Semantics on a Graph with a record multiplier
I am using Akka Streams 2.4.8 against Kafka and trying to construct graphs with At Least Once Delivery Semantics. Several of my graphs start out with something like the following:

```<code> committableSource ~> processing ~> mapOneRecordToNOtherRecords ~> ...
</code>```

where mapOneRecordToNOtherRecords takes a single message and transforms it into an arbitrary number "N" of messages of another type to work with. That means that when I'm done with this stage, each incoming message has been multiplied into N messages, each of which has the same CommittableOffset. The issue is, in order to support ALOS, I need to wait to commit until the last of these is finished its processing step.

Now I have been using Flow#mapConcat to handle the output from mapOneRecordToNOtherRecords and continue downstream. It is my understanding that the output from mapConcat preserves order, so what I need is a graph element that collects N messages with a given correlation identifier (such as the CommittableOffset) and emits the last of them when all are collected.

The method Flow#groupBy looks interesting for this purpose, but has no shutoff valve and I don't see any criteria by which it might shed keys - nor the criteria by which it decides to emit for a given key. Other SO posts have led me to believe that its use may indeed create memory leaks.

I've been poring through docs for some other solution, but I'm not finding any. Can anyone point me to it? Surely this is a common requirement? Or do I have to build a custom GraphStage?

答:
Just in case the answer is (as I suspect) not to be found in the docs for Akka, I wrote a custom GraphStage to do it.  Here it is

```<code>/**
 * Accumulates records in order based on a propertyExtractor function and a complete function. Preserves order of incoming such that if a group of
 * messages with property value P2 completes before a group with P1, and the first P1 was pulled before the first P2, they are not pushed until the
 * P1s complete. If this has not happened within timeout, will throw a TimeoutException
 *
 * @param propertyExtractor   finds the property on the object being sent by which to track incoming
 * @param complete            establishes criteria by which the accumulated sequence of records may be emitted back to the stream
 * @param complete            (optional, default 10 seconds) duration over which stage will wait for an earlier value before throwing a
 *                                   TimeoutException
 * @tparam E                   the type of the record
 * @tparam P                   the type of the property acting as a key for the record
 */
final class AccumulateWhileNotFull[E, P](propertyExtractor: E => P, bufferFull: (Seq[E]) => Boolean, timeout: Duration = 10 seconds) extends GraphStage[FlowShape[E, Seq[E]]] {

  val in = Inlet[E]("AccumulateWhileUnchanged.in")
  val out = Outlet[Seq[E]]("AccumulateWhileUnchanged.out")

  override def shape = FlowShape.of(in, out)

  override def createLogic(inheritedAttributes: Attributes) = new GraphStageLogic(shape) {

    private val buffers = TrieMap[P, scala.collection.mutable.Builder[E, Vector[E]]]()
    private val ordering = mutable.LinkedHashSet[P]()
    private val timing = TrieMap[P, DateTime]()

    setHandlers(in, out, new InHandler with OutHandler {

      override def onPush(): Unit = {
        //add next element to the buffer it requires
        val nextElement = grab(in)
        val nextState = propertyExtractor(nextElement)
        val bufferForNextState = buffers.getOrElseUpdate(nextState, Vector.newBuilder[E])
        bufferForNextState += nextElement

        //track the next state allowed to be pushed
        ordering += nextState

        val allowedState = ordering.head
        val firstAllowedAt = timing.getOrElseUpdate(allowedState, DateTime.now)

        if (firstAllowedAt.isBefore(DateTime.now().minus(timeout.toMillis))) {
          //reset timer in case exception is to be ignored
          timing += allowedState -> DateTime.now
          throw new TimeoutException(s"Failed to process expected number of messages for property ${allowedState} within ${timeout}")
        }

        if (nextState != allowedState) {
          addToBuffersAndPull(nextState, bufferForNextState)
          val bufferForAllowedState = buffers.getOrElseUpdate(allowedState, Vector.newBuilder[E]).result().toSeq
          if (bufferFull(bufferForAllowedState)) {
            removeFromBuffersAndPush(allowedState, bufferForAllowedState)
          }
        }
        else {
          //they are the same
          val result = bufferForNextState.result().toSeq
          if (bufferFull(result)) {
            removeFromBuffersAndPush(allowedState, result)
          }
          else {
            addToBuffersAndPull(nextState, bufferForNextState)
          }
        }

      }

      private def removeFromBuffersAndPush(state: P, result: Seq[E]) = {
        buffers -= state
        ordering -= state
        timing -= state
        push(out, result)
      }

      private def addToBuffersAndPull(state: P, builder: mutable.Builder[E, Vector[E]]) = {
        buffers += state -> builder
        pull(in)
      }

      override def onPull(): Unit = {
        pull(in)
      }

      override def onUpstreamFinish(): Unit = {
        var continuing = true
        //go in order, first one not full shuts it all down
        ordering.foreach { p =>
          val result = buffers(p).result()
          continuing = continuing && bufferFull(result)
          if (continuing) {
            emit(out, result)
          }
        }
        completeStage()
      }
    })

    override def postStop(): Unit = {
      buffers.clear()
    }
  }
}
</code>```

And the integration test to back it up is

```<code>import java.util.concurrent.TimeoutException

import akka.actor.ActorSystem
import akka.stream.{ ActorMaterializer, Materializer }
import akka.stream.scaladsl.{ Flow, Source }
import akka.stream.testkit.scaladsl.TestSink
import akka.testkit.TestKit
import org.scalatest.{ FunSuiteLike, Matchers }

import scala.concurrent.duration.Duration
import scala.util.Try
import scala.concurrent.duration._

class AccumulateWhileNotFullTest extends TestKit(ActorSystem("AccumulateWhileNotFullTest")) with FunSuiteLike with Matchers {
  implicit lazy val materializer: Materializer = ActorMaterializer()

  test("test works singly") {
    var result = runBasic(List(Thing("a", 1, 1)))
    result.requestNext() should be(Seq(Thing("a", 1, 1)))
    Try(result.requestNext()).isFailure should be(true)
  }

  test("test works with never complete") {
    var result = runBasic(List(Thing("a", 1, 2)))
    Try(result.requestNext()).isFailure should be(true)
  }

  test("test resets keys") {
    var result = runBasic(List(Thing("a", 1, 1), Thing("a", 1, 1)))
    result.requestNext() should be(Seq(Thing("a", 1, 1)))
    result.requestNext() should be(Seq(Thing("a", 1, 1)))
    Try(result.requestNext()).isFailure should be(true)
  }

  test("test accumulates multiple in a row") {
    var result = runBasic(List(Thing("a", 1, 3), Thing("a", 5, 3), Thing("a", 10, 3)))
    result.requestNext() should be(Seq(Thing("a", 1, 3), Thing("a", 5, 3), Thing("a", 10, 3)))
    Try(result.requestNext()).isFailure should be(true)
  }

  test("test accumulates multiple in order") {
    var result = runBasic(List(Thing("a", 1, 3), Thing("a", 5, 3), Thing("a", 10, 3), Thing("b", 5, 2), Thing("b", 10, 2)))
    result.requestNext() should be(Seq(Thing("a", 1, 3), Thing("a", 5, 3), Thing("a", 10, 3)))
    result.requestNext() should be(Seq(Thing("b", 5, 2), Thing("b", 10, 2)))
    Try(result.requestNext()).isFailure should be(true)
  }

  test("test handles out of order correctly") {
    var result = runBasic(List(Thing("a", 1, 3), Thing("b", 5, 2), Thing("a", 5, 3), Thing("c", 5, 1), Thing("a", 10, 3), Thing("b", 10, 2)))
    result.requestNext() should be(Seq(Thing("a", 1, 3), Thing("a", 5, 3), Thing("a", 10, 3)))
    result.requestNext() should be(Seq(Thing("b", 5, 2), Thing("b", 10, 2)))
    result.requestNext() should be(Seq(Thing("c", 5, 1)))
    Try(result.requestNext()).isFailure should be(true)
  }

  test("test timeout throws exception") {
    var result = runBasic(List(Thing("a", 1, 2)), 1 seconds)
    val initalTry = Try(result.requestNext())
    initalTry.isFailure should be(true)
    initalTry.recover { case ex: Throwable => ex.getMessage should be("expected OnNext, found OnComplete") } //test probe stock exception
    Thread.sleep(1000)
    Try(result.requestNext()).recover { case ex: TimeoutException => ex.getMessage should be(s"Failed to process expected number of messages for property a within 1 seconds") }
  }

  def runBasic(things: List[Thing], timeout: Duration = 10 seconds)(implicit actorSystem: ActorSystem, materializer: Materializer) = {
    val f: Flow[Thing, Seq[Thing], _] = Flow.fromGraph(new AccumulateWhileNotFull[Thing, String](
      in => in.prop,
      vals => vals.headOption.map { v => vals.size == v.count }.getOrElse(false),
      timeout
    ))
    var result = List[Seq[Thing]]()
    Source.fromIterator(() => things.toIterator).via(f).runWith(TestSink.probe(actorSystem))

  }

  case class Thing(prop: String, value: Int, count: Int)

}
</code>```

Body:
I am using Akka Streams 2.4.8 against Kafka and trying to construct graphs with At Least Once Delivery Semantics. Several of my graphs start out with something like the following:

 committableSource ~> processing ~> mapOneRecordToNOtherRecords ~> ...

where mapOneRecordToNOtherRecords takes a single message and transforms it into an arbitrary number "N" of messages of another type to work with. That means that when I'm done with this stage, each incoming message has been multiplied into N messages, each of which has the same CommittableOffset. The issue is, in order to support ALOS, I need to wait to commit until the last of these is finished its processing step.

Now I have been using Flow#mapConcat to handle the output from mapOneRecordToNOtherRecords and continue downstream. It is my understanding that the output from mapConcat preserves order, so what I need is a graph element that collects N messages with a given correlation identifier (such as the CommittableOffset) and emits the last of them when all are collected.

The method Flow#groupBy looks interesting for this purpose, but has no shutoff valve and I don't see any criteria by which it might shed keys - nor the criteria by which it decides to emit for a given key. Other SO posts have led me to believe that its use may indeed create memory leaks.

I've been poring through docs for some other solution, but I'm not finding any. Can anyone point me to it? Surely this is a common requirement? Or do I have to build a custom GraphStage?

Body:
Just in case the answer is (as I suspect) not to be found in the docs for Akka, I wrote a custom GraphStage to do it.  Here it is

/**
 * Accumulates records in order based on a propertyExtractor function and a complete function. Preserves order of incoming such that if a group of
 * messages with property value P2 completes before a group with P1, and the first P1 was pulled before the first P2, they are not pushed until the
 * P1s complete. If this has not happened within timeout, will throw a TimeoutException
 *
 * @param propertyExtractor   finds the property on the object being sent by which to track incoming
 * @param complete            establishes criteria by which the accumulated sequence of records may be emitted back to the stream
 * @param complete            (optional, default 10 seconds) duration over which stage will wait for an earlier value before throwing a
 *                                   TimeoutException
 * @tparam E                   the type of the record
 * @tparam P                   the type of the property acting as a key for the record
 */
final class AccumulateWhileNotFull[E, P](propertyExtractor: E => P, bufferFull: (Seq[E]) => Boolean, timeout: Duration = 10 seconds) extends GraphStage[FlowShape[E, Seq[E]]] {

  val in = Inlet[E]("AccumulateWhileUnchanged.in")
  val out = Outlet[Seq[E]]("AccumulateWhileUnchanged.out")

  override def shape = FlowShape.of(in, out)

  override def createLogic(inheritedAttributes: Attributes) = new GraphStageLogic(shape) {

    private val buffers = TrieMap[P, scala.collection.mutable.Builder[E, Vector[E]]]()
    private val ordering = mutable.LinkedHashSet[P]()
    private val timing = TrieMap[P, DateTime]()

    setHandlers(in, out, new InHandler with OutHandler {

      override def onPush(): Unit = {
        //add next element to the buffer it requires
        val nextElement = grab(in)
        val nextState = propertyExtractor(nextElement)
        val bufferForNextState = buffers.getOrElseUpdate(nextState, Vector.newBuilder[E])
        bufferForNextState += nextElement

        //track the next state allowed to be pushed
        ordering += nextState

        val allowedState = ordering.head
        val firstAllowedAt = timing.getOrElseUpdate(allowedState, DateTime.now)

        if (firstAllowedAt.isBefore(DateTime.now().minus(timeout.toMillis))) {
          //reset timer in case exception is to be ignored
          timing += allowedState -> DateTime.now
          throw new TimeoutException(s"Failed to process expected number of messages for property ${allowedState} within ${timeout}")
        }

        if (nextState != allowedState) {
          addToBuffersAndPull(nextState, bufferForNextState)
          val bufferForAllowedState = buffers.getOrElseUpdate(allowedState, Vector.newBuilder[E]).result().toSeq
          if (bufferFull(bufferForAllowedState)) {
            removeFromBuffersAndPush(allowedState, bufferForAllowedState)
          }
        }
        else {
          //they are the same
          val result = bufferForNextState.result().toSeq
          if (bufferFull(result)) {
            removeFromBuffersAndPush(allowedState, result)
          }
          else {
            addToBuffersAndPull(nextState, bufferForNextState)
          }
        }

      }

      private def removeFromBuffersAndPush(state: P, result: Seq[E]) = {
        buffers -= state
        ordering -= state
        timing -= state
        push(out, result)
      }

      private def addToBuffersAndPull(state: P, builder: mutable.Builder[E, Vector[E]]) = {
        buffers += state -> builder
        pull(in)
      }

      override def onPull(): Unit = {
        pull(in)
      }

      override def onUpstreamFinish(): Unit = {
        var continuing = true
        //go in order, first one not full shuts it all down
        ordering.foreach { p =>
          val result = buffers(p).result()
          continuing = continuing && bufferFull(result)
          if (continuing) {
            emit(out, result)
          }
        }
        completeStage()
      }
    })

    override def postStop(): Unit = {
      buffers.clear()
    }
  }
}

And the integration test to back it up is

import java.util.concurrent.TimeoutException

import akka.actor.ActorSystem
import akka.stream.{ ActorMaterializer, Materializer }
import akka.stream.scaladsl.{ Flow, Source }
import akka.stream.testkit.scaladsl.TestSink
import akka.testkit.TestKit
import org.scalatest.{ FunSuiteLike, Matchers }

import scala.concurrent.duration.Duration
import scala.util.Try
import scala.concurrent.duration._

class AccumulateWhileNotFullTest extends TestKit(ActorSystem("AccumulateWhileNotFullTest")) with FunSuiteLike with Matchers {
  implicit lazy val materializer: Materializer = ActorMaterializer()

  test("test works singly") {
    var result = runBasic(List(Thing("a", 1, 1)))
    result.requestNext() should be(Seq(Thing("a", 1, 1)))
    Try(result.requestNext()).isFailure should be(true)
  }

  test("test works with never complete") {
    var result = runBasic(List(Thing("a", 1, 2)))
    Try(result.requestNext()).isFailure should be(true)
  }

  test("test resets keys") {
    var result = runBasic(List(Thing("a", 1, 1), Thing("a", 1, 1)))
    result.requestNext() should be(Seq(Thing("a", 1, 1)))
    result.requestNext() should be(Seq(Thing("a", 1, 1)))
    Try(result.requestNext()).isFailure should be(true)
  }

  test("test accumulates multiple in a row") {
    var result = runBasic(List(Thing("a", 1, 3), Thing("a", 5, 3), Thing("a", 10, 3)))
    result.requestNext() should be(Seq(Thing("a", 1, 3), Thing("a", 5, 3), Thing("a", 10, 3)))
    Try(result.requestNext()).isFailure should be(true)
  }

  test("test accumulates multiple in order") {
    var result = runBasic(List(Thing("a", 1, 3), Thing("a", 5, 3), Thing("a", 10, 3), Thing("b", 5, 2), Thing("b", 10, 2)))
    result.requestNext() should be(Seq(Thing("a", 1, 3), Thing("a", 5, 3), Thing("a", 10, 3)))
    result.requestNext() should be(Seq(Thing("b", 5, 2), Thing("b", 10, 2)))
    Try(result.requestNext()).isFailure should be(true)
  }

  test("test handles out of order correctly") {
    var result = runBasic(List(Thing("a", 1, 3), Thing("b", 5, 2), Thing("a", 5, 3), Thing("c", 5, 1), Thing("a", 10, 3), Thing("b", 10, 2)))
    result.requestNext() should be(Seq(Thing("a", 1, 3), Thing("a", 5, 3), Thing("a", 10, 3)))
    result.requestNext() should be(Seq(Thing("b", 5, 2), Thing("b", 10, 2)))
    result.requestNext() should be(Seq(Thing("c", 5, 1)))
    Try(result.requestNext()).isFailure should be(true)
  }

  test("test timeout throws exception") {
    var result = runBasic(List(Thing("a", 1, 2)), 1 seconds)
    val initalTry = Try(result.requestNext())
    initalTry.isFailure should be(true)
    initalTry.recover { case ex: Throwable => ex.getMessage should be("expected OnNext, found OnComplete") } //test probe stock exception
    Thread.sleep(1000)
    Try(result.requestNext()).recover { case ex: TimeoutException => ex.getMessage should be(s"Failed to process expected number of messages for property a within 1 seconds") }
  }

  def runBasic(things: List[Thing], timeout: Duration = 10 seconds)(implicit actorSystem: ActorSystem, materializer: Materializer) = {
    val f: Flow[Thing, Seq[Thing], _] = Flow.fromGraph(new AccumulateWhileNotFull[Thing, String](
      in => in.prop,
      vals => vals.headOption.map { v => vals.size == v.count }.getOrElse(false),
      timeout
    ))
    var result = List[Seq[Thing]]()
    Source.fromIterator(() => things.toIterator).via(f).runWith(TestSink.probe(actorSystem))

  }

  case class Thing(prop: String, value: Int, count: Int)

}


问:
Codeigniter db_where in 3 joined tables
So this code is a combination of 3 table joined, now i want to filter the query where only the request that a user can have is his/her own request and not from other user.. the problem is in where clause i have duplicated.</p>

```<code>$this->db->order_by('loanrequest.ApplicationNo', 'DESC');
        $query = $this->db->get('loanrequest','loanapplication','user');
        $this->db->join('loanapplication','loanrequest.ApplicationNo = loanapplication.ApplicationNo');
        $this->db->join('user', 'user.userId = loanapplication.userId');
        $this->db->where('loanapplication.userId', $this->session->userdata('userId'));
        $this->db->where('loanapplication.ApplicationNo', 'loanrequest.ApplicationNo');
        return $query->result_array();
</code>```

答:
I can not get what you have done in your join query but Here is how I do join in my CodeIgniter model.

You don't need to put this in where condition:

$this->db->where('loanapplication.ApplicationNo', 'loanrequest.ApplicationNo');

Because you have already done that in the join query.

```<code>$query = $this->db->select('*')
            ->from('loanapplication')
            ->join('loanrequest', 'loanrequest.ApplicationNo  = loanapplication.ApplicationNo', 'left')
            ->join('user', 'user.userId  = loanapplication.userId', 'left')
            ->where_in('loanapplication.userId',$this->session->userdata('userId'))
            ->order_by('loanrequest.ApplicationNo', 'DESC')
            ->get();

return $query->result_array();
</code>```

I will recommend you should use $this->db->last_query() because it gives you a better idea about your query.

Title: Codeigniter db_where in 3 joined tables

Body:
So this code is a combination of 3 table joined, now i want to filter the query where only the request that a user can have is his/her own request and not from other user.. the problem is in where clause i have duplicated.

$this->db->order_by('loanrequest.ApplicationNo', 'DESC');
        $query = $this->db->get('loanrequest','loanapplication','user');
        $this->db->join('loanapplication','loanrequest.ApplicationNo = loanapplication.ApplicationNo');
        $this->db->join('user', 'user.userId = loanapplication.userId');
        $this->db->where('loanapplication.userId', $this->session->userdata('userId'));
        $this->db->where('loanapplication.ApplicationNo', 'loanrequest.ApplicationNo');
        return $query->result_array();

Body:
I can not get what you have done in your join query but Here is how I do join in my CodeIgniter model.

You don't need to put this in where condition:

$this->db->where('loanapplication.ApplicationNo', 'loanrequest.ApplicationNo');

Because you have already done that in the join query.

$query = $this->db->select('*')
            ->from('loanapplication')
            ->join('loanrequest', 'loanrequest.ApplicationNo  = loanapplication.ApplicationNo', 'left')
            ->join('user', 'user.userId  = loanapplication.userId', 'left')
            ->where_in('loanapplication.userId',$this->session->userdata('userId'))
            ->order_by('loanrequest.ApplicationNo', 'DESC')
            ->get();

return $query->result_array();

I will recommend you should use $this->db->last_query() because it gives you a better idea about your query.


问:
How to calculate two dataframe'value with scala in spark
I hava two dataframe ,the count of two dataframe is same,I want to get the sum of each value in two dataframe
this is input:

```<code>+---+  and       +---+
|df1|            |df2|
+---+            +---+
| 11|            |  1|
| 12|            |  2|
| 13|            |  3|
| 14|            |  4|
| 15|            |  5|
| 16|            |  6|
| 17|            |  7|
| 18|            |  8|
| 19|            |  9|
| 20|            | 10|
+---+            +---+
</code>```

this is my code:

```<code>val df1 = sc.parallelize(1 to 10,2).toDF("df1")
    val df2 = sc.parallelize(11 to 20,2).toDF("df2")
    val df3=df1.rdd.zip(df2.rdd).map(x=>{
      x._1.getInt(0)+x._2.getInt(0)
    }).toDF("result")
    df3.show()
</code>```

the result is:

```<code>+-----+
|result|
+-----+
|   12|
|   14|
|   16|
|   18|
|   20|
|   22|
|   24|
|   26|
|   28|
|   30|
+-----+
</code>```

I have to change dataframe to rdd then zip two rdd,how to calculate two dataframe with not transform to rdd?

答:
You can use monotonically_increasing_id() to give an id for both dataframe and join with adding two columns.

```<code>import spark.implicits._
val df1 = spark.sparkContext.parallelize(11 to 20).toDF("df1")
val df2 = spark.sparkContext.parallelize((1 to 10 )).toDF("df2")

df1.withColumn("id", monotonically_increasing_id())
  .join(df2.withColumn("id", monotonically_increasing_id()), "id")
  .withColumn("result", ($"df1" + $"df2")).drop("id").show
</code>```

Output:

```<code>+---+---+------+
|df1|df2|result|
+---+---+------+
| 11|  1|    12|
| 18|  8|    26|
| 17|  7|    24|
| 20| 10|    30|
| 16|  6|    22|
| 12|  2|    14|
| 14|  4|    18|
| 19|  9|    28|
| 13|  3|    16|
| 15|  5|    20|
+---+---+------+
</code>```

Hope this helps!

Body:
I hava two dataframe ,the count of two dataframe is same,I want to get the sum of each value in two dataframe
this is input:

+---+  and       +---+
|df1|            |df2|
+---+            +---+
| 11|            |  1|
| 12|            |  2|
| 13|            |  3|
| 14|            |  4|
| 15|            |  5|
| 16|            |  6|
| 17|            |  7|
| 18|            |  8|
| 19|            |  9|
| 20|            | 10|
+---+            +---+

this is my code:

val df1 = sc.parallelize(1 to 10,2).toDF("df1")
    val df2 = sc.parallelize(11 to 20,2).toDF("df2")
    val df3=df1.rdd.zip(df2.rdd).map(x=>{
      x._1.getInt(0)+x._2.getInt(0)
    }).toDF("result")
    df3.show()

the result is:

+-----+
|result|
+-----+
|   12|
|   14|
|   16|
|   18|
|   20|
|   22|
|   24|
|   26|
|   28|
|   30|
+-----+

I have to change dataframe to rdd then zip two rdd,how to calculate two dataframe with not transform to rdd?

Body:
You can use monotonically_increasing_id() to give an id for both dataframe and join with adding two columns.

import spark.implicits._
val df1 = spark.sparkContext.parallelize(11 to 20).toDF("df1")
val df2 = spark.sparkContext.parallelize((1 to 10 )).toDF("df2")

df1.withColumn("id", monotonically_increasing_id())
  .join(df2.withColumn("id", monotonically_increasing_id()), "id")
  .withColumn("result", ($"df1" + $"df2")).drop("id").show

Output:

+---+---+------+
|df1|df2|result|
+---+---+------+
| 11|  1|    12|
| 18|  8|    26|
| 17|  7|    24|
| 20| 10|    30|
| 16|  6|    22|
| 12|  2|    14|
| 14|  4|    18|
| 19|  9|    28|
| 13|  3|    16|
| 15|  5|    20|
+---+---+------+

Hope this helps!


问:
How do I display my database in table form using PHP html?
How do I display my database in table form. Here my code:

```<code><?php

$link=mysqli_connect("localhost","root","");
mysqli_select_db($link,"order");
$res=mysqli_query($link,"select * from ordersum");
while($row=mysqli_fetch_array($res))
{

echo $row["name"]." ".$row["email"]." ".$row["content"]." ".$row["date"]." ".$row["amount"];
echo "<br>";

}

?>
</code>```

答:
Try this, hope can help you.</p>

```<code><table>
        <thead>
            <tr>
                <th>Name</th>
                <th>Email</th>
                <th>Content</th>
                <th>Date</th>
                <th>Amount</th>
            </tr>
        </thead>
    <tbody>

<?php
   $link=mysqli_connect("localhost","root","");
   mysqli_select_db($link,"order");
   $res=mysqli_query($link,"select * from ordersum");

   while($row=mysqli_fetch_array($res)){
        echo "<tr>
              <td>".$row["name"]."</td>
              <td>".$row["email"]."</td>
              <td>".$row["content"]."</td>
              <td>".$row["date"]."</td>
              <td>".$row["amount"]."</td>
              </tr>";
   }
?>
   </tbody>
</table>
</code>```

Body:
How do I display my database in table form. Here my code:

<?php

$link=mysqli_connect("localhost","root","");
mysqli_select_db($link,"order");
$res=mysqli_query($link,"select * from ordersum");
while($row=mysqli_fetch_array($res))
{

echo $row["name"]." ".$row["email"]." ".$row["content"]." ".$row["date"]." ".$row["amount"];
echo "
";

}

?>

Body:
Try this, hope can help you.

<table>
        <thead>
            <tr>
                <th>Name</th>
                <th>Email</th>
                <th>Content</th>
                <th>Date</th>
                <th>Amount</th>
            </tr>
        </thead>
    <tbody>

<?php
   $link=mysqli_connect("localhost","root","");
   mysqli_select_db($link,"order");
   $res=mysqli_query($link,"select * from ordersum");

   while($row=mysqli_fetch_array($res)){
        echo "<tr>
              <td>".$row["name"]."</td>
              <td>".$row["email"]."</td>
              <td>".$row["content"]."</td>
              <td>".$row["date"]."</td>
              <td>".$row["amount"]."</td>
              </tr>";
   }
?>
   </tbody>
</table>


问:
Hide entire row if the same value on col A and B
If the same value on col A and B in the same row like 5 5 or 22 22
then I'd like to hide entire row or unfilter those rows. </p>

```<code>sub myExample
    dim filter_Z as range, rowW as range, COLA as range, COLB as range

    dim last_row as long

    Set filter_Z = Sheets(1).Range("A1" & last_row)

    '
    For Each rowW In filter_Z.SpecialCells(xlCellTypeVisible)
    '
    COLA = ActiveWorkbook.Worksheets("MySheets1").Range("A" & rowW.Row).Value
    COLB = ActiveWorkbook.Worksheets("MySheets1").").Range("B" & rowW.Row).Value

    If COLA=COLB Then rowW.EntireRow.Hidden = True

     Next rowW
end sub
</code>```

答:
This should at least point you in the correct direction:</p>

```<code>Option Explicit
Sub hideRows()
    Application.ScreenUpdating = False
    Dim sh As Worksheet, rw As Range
    Set sh = ActiveSheet

    For Each rw In sh.Rows
        If sh.Cells(rw.Row, 1).Value And sh.Cells(rw.Row, 2).Value = "" Then
            Exit For
        End If

        If sh.Cells(rw.Row, 1).Value = sh.Cells(rw.Row, 2).Value Then
            rw.EntireRow.Hidden = True
        End If
    Next rw

    Application.ScreenUpdating = True
End Sub
</code>```

Body:
If the same value on col A and B in the same row like 5 5 or 22 22
then I'd like to hide entire row or unfilter those rows.

sub myExample
    dim filter_Z as range, rowW as range, COLA as range, COLB as range

    dim last_row as long

    Set filter_Z = Sheets(1).Range("A1" & last_row)

    '
    For Each rowW In filter_Z.SpecialCells(xlCellTypeVisible)
    '
    COLA = ActiveWorkbook.Worksheets("MySheets1").Range("A" & rowW.Row).Value
    COLB = ActiveWorkbook.Worksheets("MySheets1").").Range("B" & rowW.Row).Value

    If COLA=COLB Then rowW.EntireRow.Hidden = True

     Next rowW
end sub

Body:
This should at least point you in the correct direction:

Option Explicit
Sub hideRows()
    Application.ScreenUpdating = False
    Dim sh As Worksheet, rw As Range
    Set sh = ActiveSheet

    For Each rw In sh.Rows
        If sh.Cells(rw.Row, 1).Value And sh.Cells(rw.Row, 2).Value = "" Then
            Exit For
        End If

        If sh.Cells(rw.Row, 1).Value = sh.Cells(rw.Row, 2).Value Then
            rw.EntireRow.Hidden = True
        End If
    Next rw

    Application.ScreenUpdating = True
End Sub


问:
Parse JSON in websocket sharp
I'm trying to parse JSON string that received from websocket sharp but keep failing.

```<code>using (var ws = new WebSocket(WebAddr))
{
    ws.Log.Level = LogLevel.Debug;
    ws.OnOpen += (ss, ee) =>
    {
        System.IO.File.WriteAllText(@"C:\log.txt", "connected!");
    };
    ws.OnMessage +=  (ss, ee) =>
    {
        JsonValue jo = JsonValue.Parse(ee.Data);
        string value = (string)jo["levelid"];
        Console.Write(value + '\n');
    };
}
</code>```

It just threw exception error when reaches string value... part.

I'm using System.Json from nuget.

答:
I think I figured it out. The server will respond with 2 messages, one is Json object and one is Json array.

dynamic jo = JsonConvert.DeserializeObject(ee.Data);

This fixed my problem!

Title: Parse JSON in websocket sharp

Body:
I'm trying to parse JSON string that received from websocket sharp but keep failing.

using (var ws = new WebSocket(WebAddr))
{
    ws.Log.Level = LogLevel.Debug;
    ws.OnOpen += (ss, ee) =>
    {
        System.IO.File.WriteAllText(@"C:\log.txt", "connected!");
    };
    ws.OnMessage +=  (ss, ee) =>
    {
        JsonValue jo = JsonValue.Parse(ee.Data);
        string value = (string)jo["levelid"];
        Console.Write(value + '\n');
    };
}

It just threw exception error when reaches string value... part.

I'm using System.Json from nuget.


问:
sceneKit dynamic physic body fall through floor
I have a cube with dynamic physical body and a plane with kinematic physic body.When I place a cube above plane, it will fall onto plane and a bounce is expected.

The PROBLEM is: when the cube is small or light, it just go through plane.For instance, cube has 0.1*0.1*0.1 work fine but 0.05*0.05*0.05 sucks.In this case I still get physical body contacting notification.

this is my code for creating geometry:

```<code>//cube
//when dimension is 0.1 everything is fine
float dimension = 0.05;
SCNBox *cube = [SCNBox boxWithWidth:dimension height:dimension length:dimension chamferRadius:0];
cube.materials = @[material];
SCNNode *node = [SCNNode nodeWithGeometry:cube];
node.physicsBody = [SCNPhysicsBody bodyWithType:SCNPhysicsBodyTypeDynamic shape:nil];
node.physicsBody.mass = 1;
node.physicsBody.categoryBitMask = phsicBodyCategoryCube;
node.physicsBody.collisionBitMask = phsicBodyCategoryPlane;
node.physicsBody.contactTestBitMask = phsicBodyCategoryPlane;

//plane
self.planeGeometry = [SCNBox boxWithWidth:100 height:0.01 length:100 chamferRadius:0
plane.physicsBody = [SCNPhysicsBody bodyWithType:SCNPhysicsBodyTypeKinematic
                    shape: [SCNPhysicsShape shapeWithGeometry:self.planeGeometry options:nil]];
plane.physicsBody.categoryBitMask = phsicBodyCategoryPlane;
plane.physicsBody.collisionBitMask = phsicBodyCategoryCube;
plane.physicsBody.contactTestBitMask = phsicBodyCategoryCube;
</code>```

答:
I’m surprised you’re getting collisions at all. See the SCNPhysicsBodyType docs – the kinematic type is for bodies that you move (by setting their position, etc) to cause collisions, but that aren’t themselves affected by other bodies colliding with them.

If you set the floor’s type to static, you’ll probably see better results. A static body doesn’t move (either as a result of physics interactions, or by you setting its position), so the physics engine can more accurately check for other bodies colliding with it.

edit: Other things to look into:

Use a SCNPlane rather than a SCNBox for your floor. (Note that you can create physics bodies with shapes different from their visible geometry, if that helps.) I'm not sure about SceneKit's, but it's easier for a lot of physics engines to check "has some object passed this infinite boundary since the last frame?" than "is some object inside this finite region on this frame?"

Enable precise collision detection for your moving objects.

Body:
I have a cube with dynamic physical body and a plane with kinematic physic body.When I place a cube above plane, it will fall onto plane and a bounce is expected.

The PROBLEM is: when the cube is small or light, it just go through plane.For instance, cube has 0.1*0.1*0.1 work fine but 0.05*0.05*0.05 sucks.In this case I still get physical body contacting notification.

this is my code for creating geometry:

//cube
//when dimension is 0.1 everything is fine
float dimension = 0.05;
SCNBox *cube = [SCNBox boxWithWidth:dimension height:dimension length:dimension chamferRadius:0];
cube.materials = @[material];
SCNNode *node = [SCNNode nodeWithGeometry:cube];
node.physicsBody = [SCNPhysicsBody bodyWithType:SCNPhysicsBodyTypeDynamic shape:nil];
node.physicsBody.mass = 1;
node.physicsBody.categoryBitMask = phsicBodyCategoryCube;
node.physicsBody.collisionBitMask = phsicBodyCategoryPlane;
node.physicsBody.contactTestBitMask = phsicBodyCategoryPlane;

//plane
self.planeGeometry = [SCNBox boxWithWidth:100 height:0.01 length:100 chamferRadius:0
plane.physicsBody = [SCNPhysicsBody bodyWithType:SCNPhysicsBodyTypeKinematic
                    shape: [SCNPhysicsShape shapeWithGeometry:self.planeGeometry options:nil]];
plane.physicsBody.categoryBitMask = phsicBodyCategoryPlane;
plane.physicsBody.collisionBitMask = phsicBodyCategoryCube;
plane.physicsBody.contactTestBitMask = phsicBodyCategoryCube;


问:
React/Express - 'Unexpected token <' in call to renderToString()
I'm working on setting up server-side rendering for my React/Express app, but I'm encountering a syntax error relating to the call to the react-dom/server renderToString() method.  I'm loosely following this tutorial - http://crypt.codemancers.com/posts/2016-09-16-react-server-side-rendering/

index.js (Express app root):

```<code>'use strict'
require('babel-register')({
    presets: ['es2015', 'react']
});

const express = require('express')
const path = require('path')
const app = express()
const React = require('react')
const reactDomServer = require('react-dom/server')
const routes = require('./src/routes.jsx')
const reactRouter = require('react-router')
let { match, RouterContext } = reactRouter

app.get('*', (req, res) => {
    match({ routes: routes, location: req.url }, (err, redirect, props) => {
        const appHtml = reactDomServer.renderToString(<RouterContext {...props}/>)
        res.send(renderPage(appHtml))
    })
})
</code>```

However, this causes the error:

```<code>const appHtml = reactDomServer.renderToString(<RouterContext {...props}/>)
                                              ^
SyntaxError: Unexpected token <
</code>```

All of the similar examples that I've seen have a straight JSX component dropped in... what am I missing?

答:
babel-register doesn't process the file it is called from, see https://stackoverflow.com/a/29425761/1795821

You'll need to put the app.get() called into another file, or use a different method of loading Babel.

So make a new renderReact.js file with

```<code>module.exports = function(app) {
  app.get('*', (req, res) => {
    match({ routes: routes, location: req.url }, (err, redirect, props) => {
        const appHtml = reactDomServer.renderToString(<RouterContext {...props}/>)
        res.send(renderPage(appHtml))
    })
  })
}
</code>```

Then back in your index.js do this instead

```<code>let renderReact = require('./renderReact.js');
renderReact(app);
</code>```

Body:
I'm working on setting up server-side rendering for my React/Express app, but I'm encountering a syntax error relating to the call to the react-dom/server renderToString() method.  I'm loosely following this tutorial - http://crypt.codemancers.com/posts/2016-09-16-react-server-side-rendering/

index.js (Express app root):

'use strict'
require('babel-register')({
    presets: ['es2015', 'react']
});

const express = require('express')
const path = require('path')
const app = express()
const React = require('react')
const reactDomServer = require('react-dom/server')
const routes = require('./src/routes.jsx')
const reactRouter = require('react-router')
let { match, RouterContext } = reactRouter

app.get('*', (req, res) => {
    match({ routes: routes, location: req.url }, (err, redirect, props) => {
        const appHtml = reactDomServer.renderToString(<RouterContext {...props}/>)
        res.send(renderPage(appHtml))
    })
})

However, this causes the error:

const appHtml = reactDomServer.renderToString(<RouterContext {...props}/>)
                                              ^
SyntaxError: Unexpected token <

All of the similar examples that I've seen have a straight JSX component dropped in... what am I missing?

Body:
babel-register doesn't process the file it is called from, see https://stackoverflow.com/a/29425761/1795821

You'll need to put the app.get() called into another file, or use a different method of loading Babel.

So make a new renderReact.js file with

module.exports = function(app) {
  app.get('*', (req, res) => {
    match({ routes: routes, location: req.url }, (err, redirect, props) => {
        const appHtml = reactDomServer.renderToString(<RouterContext {...props}/>)
        res.send(renderPage(appHtml))
    })
  })
}

Then back in your index.js do this instead

let renderReact = require('./renderReact.js');
renderReact(app);

ContentLicense: CC BY-SA 4.0


问:
Database design to manage data from Serial Port?
I'm writing codes to capture Serial Port data (e.g. micrometer) and do the following

real time display and graphing

delete/modify/replace existing data by focus and re-measurement,

save data somewhere for additional statistical analysis (e.g. in Excel).  So out put as .csv is also an option

Because each measurement may capture hundreds to thousands of data (measurement points), I'm not sure how shall go about to design my database - shall I create a new row for each data received, or shall I push all data into an array and store as a super long string separated by a comma into the database? For such application, do I need Server 2008 or would Server 2008 Express will be sufficient. What are their pros/cons in terms of performance?

Is it possible to create such as application where client won't need to install sql server?

答:
To answer your last question first, look at SQLite because it is free open source, and I'm pretty sure their license is null. Plus nothing to install for your users. SQLite can be compiled with your code.

To answer your primary question, I would encourage using a database only if it really makes sense. Are you going to be running queries against the data, or are you just looking to store and retrieve entries by some sort of identifier? I would discourage storing it as a super long comma separated string, but instead look into the BLOB type. With BLOBs, you can put datatypes into the database so you can easily get them back out, plus I believe it is much more efficient that way. I would only suggest using TEXT type if you need to do some sort of text query on it. For example fulltext searches

ContentLicense: CC BY-SA 2.5


问:
Take value from field in Form to a new record in other Table
Would really like some guidance on this one. Not as easy as the title might say at first and I'm stuck beyond all and frustrated.

So:

I have a MainForm (With a current ID I would like to stay on!)

I have a Subform (search engine that searches in various linked excel files)

I have 2 tables; one for the Mainform, and one for Items

So on the Mainform, I display the Subform (search).
I do my search and find a specific item in the excel files
I have a command button, that I want to click save the found item in the search field, into my ItemsTable as a new record.

Currently I'm doing this:

```<code>Private Sub Command13_Click()
Forms!MainForm.Form.Item1.Value = Me.Searchresult.Value
End Sub
</code>```

This does actually post my search result into a new field and saves it into the itemsTable.

My problem: I don't need to actually have a field to post to. I just want it to write directly to my table and store it there as a NEW record. (Right now it just overwrites the previous data. Logically because its the same field every time with the same properties).

Can someone PLEASE help me with this one?

答:
Options:

set focus to the subform container then move to New Record row followed by your code, this is not simple, review https://access-programmers.co.uk/forums/showthread.php?t=127337

use SQL INSERT action then requery the subform

CurrentDb.Execute("INSERT INTO Items(Item1) VALUES('" & Me.Searchresult & "'")

Body:
Would really like some guidance on this one. Not as easy as the title might say at first and I'm stuck beyond all and frustrated.

So:

I have a MainForm (With a current ID I would like to stay on!)

I have a Subform (search engine that searches in various linked excel files)

I have 2 tables; one for the Mainform, and one for Items

So on the Mainform, I display the Subform (search).
I do my search and find a specific item in the excel files
I have a command button, that I want to click save the found item in the search field, into my ItemsTable as a new record.

Currently I'm doing this:

Private Sub Command13_Click()
Forms!MainForm.Form.Item1.Value = Me.Searchresult.Value
End Sub

This does actually post my search result into a new field and saves it into the itemsTable.

My problem: I don't need to actually have a field to post to. I just want it to write directly to my table and store it there as a NEW record. (Right now it just overwrites the previous data. Logically because its the same field every time with the same properties).

Can someone PLEASE help me with this one?