mercredi 22 avril 2015

QT : Accessing secured resources only when login is complete via REST

I am working in a QT application in which I am accessing secured resources over REST. To access secured resources, I am initially logging-in and then saving the cookie in cookieManager. Once that is done, the manager is requesting via GET the secure object.

The problem I am currently facing is because the login is not complete, and I am requesting secure resource, I am getting Access Denied in the debug logs. Because of this I guess the request is getting repeated, and I am getting the ouput multiple times.

I want to only access secure resource when the login is successful while maintaining the contents of cookieManager and not make multiple requests. I tried to do that in SLOT when request is finished, but it goes in infinite loop.

Qt code :

void Person::loginAndAccess (){

    QString url_str = "http://localhost:8080/j_spring_security_check";
    QString canvasUrl = "http://localhost:8080/rest/jsonlist";

 QNetworkAccessManager *manager = new QNetworkAccessManager();
    manager->setCookieJar (new QNetworkCookieJar(manager));
    connect (manager,SIGNAL(finished(QNetworkReply*)),this,SLOT(slotRequestFinished(QNetworkReply*)));
    QNetworkRequest request;
    request.setUrl (url_str);
    request.setRawHeader("User-Agent", "MyOwnBrowser 1.0");
    QByteArray postData;
    postData.append ("j_username=email@email.de");
    postData.append ("&j_password=password");
    manager->post (request,postData);
// From here I am accessing secured resource
    request.setUrl (canvasUrl);
    request.setRawHeader("User-Agent", "MyOwnBrowser 1.0");
    manager->get (request);
}

void Person::slotRequestFinished(QNetworkReply *reply)
{

    reply->deleteLater();

        if(reply->error() == QNetworkReply::NoError) {
            // Get the http status code
            int v = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
            if (v >= 200 && v < 300) // Success
            {
                 // Here we got the final reply
                qDebug() << "Request was successful";
                QString replyText = reply->readAll();
                qDebug() << replyText;
                return;
            }
            else if (v >= 300 && v < 400) // Redirection
            {
                // Get the redirection url
                QUrl newUrl = reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl();
                // Because the redirection url can be relative,
                // we have to use the previous one to resolve it
                newUrl = reply->url().resolved(newUrl);

                QNetworkAccessManager *manager = reply->manager();
                QNetworkRequest redirection(newUrl);
                QNetworkReply *newReply = manager->get(redirection);
                QString reply = newReply->readAll ();
                qDebug() << reply;

                return; // to keep the manager for the next request
            }
        }
        else
        {
            // Error
            qDebug() << reply->errorString();

        }

        reply->manager()->deleteLater();
}

Output in QT :

""
""
Request was successful
"
// REPLY from Server ommitted from output

"
Request was successful
""
Request was successful
"
// Again reply from server cut off

"
Request was successful
""
Request was successful
"

// So on and so-forth.

What am I doing wrong. I am not that much expert in QT, any help would be nice. Thanks a lot.

How i can extract PIXEL from DICOM file?

I want to write a script to extract the PixelDATA of a DICOM file using c or c ++, I don't want to use external libraries like dicomsdl... if anyone can help me to write algorithm for extract and show image .

Drawing html with transparent background

I'm currently trying to draw an HTML formatted text of a QTextEdit into a QPixmap with a transparent background, to use it as an overlay for another widget.

My first attempt was, to use the QTextDocument of the QTextEdit and use drawContents() to draw it to a QPixmap.

As a second attempt, I passed the HTML to a QStaticText and painted this to my QPixmap, using a QPainter.

Both approaches paint the final text as expected, however, the background of the QPixmap is always grey. Also setting the background-color of the QTextEdit, inside the StyleSheet, to transparent does no change.

Is there any way, that I can make the background transparent?

Spring MVC : Controller redirecting to JSP page instead of giving Object via REST

I am working on a Spring-MVC application in which I am trying to access secured services over a QT application. I am successfully able to login and gain access to secured resources, but when I call a controller method which is designed to give back an array of the Objects requested, it sends back the entire JSP page via REST. Why is this happening and how can I remedy this situation??

Controller code :

@PreAuthorize("hasRole('ROLE_USER')")
    @RequestMapping(value = "/canvas/jsonlist", method = RequestMethod.GET)
    public @ResponseBody Canvas[] listJsonCanvas() {
        System.out.println("From rest authentication the username is "+this.personService.returnLoggedInUsersEmail());
        List<Canvas> canvasList = this.canvasService.listCanvasPerson();
        return canvasList.toArray(new Canvas[canvasList.size()]);
    }

Output is JSP page, so I am not pasting it here.

Security-application-context.xml :

 <import resource="servlet-context.xml" />

    <!-- Global Security settings -->
    <security:global-method-security pre-post-annotations="enabled" />
    <security:http pattern="/resources/**" security="none"/>

    <security:http create-session="ifRequired" use-expressions="true" auto-config="false" disable-url-rewriting="true">
        <security:form-login login-page="/login" login-processing-url="/j_spring_security_check" default-target-url="/canvas/list" always-use-default-target="false" authentication-failure-url="/denied.jsp" />
        <security:remember-me key="_spring_security_remember_me" user-service-ref="userDetailsService" token-validity-seconds="1209600" data-source-ref="dataSource"/>
        <security:logout delete-cookies="JSESSIONID" invalidate-session="true" logout-url="/j_spring_security_logout"/>
<!--    <security:intercept-url pattern="/**" requires-channel="https"/> -->
    <security:port-mappings>
        <security:port-mapping http="80" https="443"/>
    </security:port-mappings>
    <security:logout logout-url="/logout" logout-success-url="/" success-handler-ref="myLogoutHandler"/>

     <security:session-management session-fixation-protection="migrateSession">
         <security:concurrency-control session-registry-ref="sessionRegistry" max-sessions="1" expired-url="/login"/>
     </security:session-management>

    </security:http>

    <bean id="sessionRegistry" class="org.springframework.security.core.session.SessionRegistryImpl" />

    <!-- Rest authentication, don't edit, delete, add-->
    <bean id="springSecurityFilterChain" class="org.springframework.security.web.FilterChainProxy">

    <security:filter-chain-map path-type="ant">
        <security:filter-chain filters="persistencefilter,authenticationfilter" pattern="/login"/>
        <security:filter-chain filters="persistencefilter,logoutfilter" pattern="/logout"/>
        <security:filter-chain pattern="/rest/**" filters="persistencefilter,restfilter" />
    </security:filter-chain-map>
    </bean>

    <bean id="persistencefilter" class="org.springframework.security.web.context.SecurityContextPersistenceFilter"/>

    <bean id="authenticationfilter" class="com.journaldev.spring.utility.AuthenticationFilter">
        <property name="authenticationManager" ref="authenticationManager"/>
        <property name="authenticationSuccessHandler" ref="myAuthSuccessHandler"/>
        <property name="passwordParameter" value="pass"/>
        <property name="usernameParameter" value="user"/>
        <property name="postOnly" value="false"/>
    </bean>

    <bean id="myAuthSuccessHandler" class="com.journaldev.spring.utility.AuthenticationSuccessHandler"/>

    <bean id="myLogoutHandler" class="com.journaldev.spring.utility.MyLogoutHandler"/>

    <bean id="logoutfilter" class="org.springframework.security.web.authentication.logout.LogoutFilter">

        <constructor-arg index="0" value="/"/>
        <constructor-arg index="1">
            <list>
                <bean class="org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler">
                    <property name="invalidateHttpSession" value="true"/>
                    <property name="clearAuthentication" value="true"/>
                </bean>
                <bean id="myLogoutHandler" class="com.journaldev.spring.utility.MyLogoutHandler"/>
            </list>
        </constructor-arg>
    </bean>

    <bean id="httpRequestAccessDecisionManager" class="org.springframework.security.access.vote.AffirmativeBased">
        <property name="allowIfAllAbstainDecisions" value="false"/>
        <property name="decisionVoters">
            <list>
                <ref bean="roleVoter"/>
            </list>
        </property>
    </bean>

    <bean id="roleVoter" class="org.springframework.security.access.vote.RoleVoter"/>

    <bean id="restfilter" class="org.springframework.security.web.access.intercept.FilterSecurityInterceptor">
        <property name="authenticationManager" ref="authenticationManager"/>
        <property name="accessDecisionManager" ref="httpRequestAccessDecisionManager"/>
        <property name="securityMetadataSource">
            <security:filter-invocation-definition-source>
                <security:intercept-url pattern="/rest/**" access="ROLE_USER"/>
            </security:filter-invocation-definition-source>
        </property>
    </bean>
    <!-- Rest authentication ends here-->

    <!-- queries to be run on data -->
    <beans:bean id="rememberMeAuthenticationProvider" class="org.springframework.security.web.authentication.rememberme.PersistentTokenBasedRememberMeServices">
        <beans:property name="key" value="_spring_security_remember_me" />
        <beans:property name="tokenRepository" ref="jdbcTokenRepository"/>
        <beans:property name="userDetailsService" ref="LoginServiceImpl"/>
    </beans:bean>

    <!--Database management for remember-me -->
    <beans:bean id="jdbcTokenRepository"
                class="org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl">
        <beans:property name="createTableOnStartup" value="false"/>
        <beans:property name="dataSource" ref="dataSource" />
    </beans:bean>

    <!-- Remember me ends here -->
    <security:authentication-manager alias="authenticationManager">
        <security:authentication-provider user-service-ref="LoginServiceImpl">
           <security:password-encoder  ref="encoder"/>
        </security:authentication-provider>
    </security:authentication-manager>

    <beans:bean id="encoder"
                class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder">
        <beans:constructor-arg name="strength" value="11" />
    </beans:bean>

    <beans:bean id="daoAuthenticationProvider"
                class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
                <beans:property name="userDetailsService" ref="LoginServiceImpl"/>
               <beans:property name="passwordEncoder" ref="encoder"/>
    </beans:bean>
</beans>

Debug output :

DEBUG: org.springframework.web.servlet.DispatcherServlet - Rendering view [org.springframework.web.servlet.view.JstlView: name 'login'; URL [/WEB-INF/views/login.jsp]] in DispatcherServlet with name 'appServlet'
DEBUG: org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor - Previously Authenticated: org.springframework.security.authentication.UsernamePasswordAuthenticationToken@99f857e1: Principal: org.springframework.security.core.userdetails.User@dde5c0af: Username: email@email.de; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_USER; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@957e: RemoteIpAddress: 127.0.0.1; SessionId: null; Granted Authorities: ROLE_USER
DEBUG: org.springframework.web.servlet.view.JstlView - Added model object 'person' of type [com.journaldev.spring.model.Person] to request in view with name 'login'
DEBUG: org.springframework.web.servlet.view.JstlView - Added model object 'org.springframework.validation.BindingResult.person' of type [org.springframework.validation.BeanPropertyBindingResult] to request in view with name 'login'
DEBUG: org.springframework.security.access.vote.AffirmativeBased - Voter: org.springframework.security.access.prepost.PreInvocationAuthorizationAdviceVoter@5d046f29, returned: 1
DEBUG: org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor - Authorization successful
DEBUG: org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor - RunAsManager did not change Authentication object
DEBUG: org.springframework.web.servlet.view.JstlView - Forwarding to resource [/WEB-INF/views/login.jsp] in InternalResourceView 'login'
From rest authentication the username is email@email.de
DEBUG: org.springframework.web.servlet.DispatcherServlet - Rendering view [org.springframework.web.servlet.view.JstlView: name 'canvas'; URL [/WEB-INF/views/canvas.jsp]] in DispatcherServlet with name 'appServlet'
DEBUG: org.springframework.web.servlet.view.JstlView - Added model object 'canvases' of type [com.journaldev.spring.model.Canvas] to request in view with name 'canvas'
DEBUG: org.springframework.web.servlet.view.JstlView - Added model object 'org.springframework.validation.BindingResult.canvases' of type [org.springframework.validation.BeanPropertyBindingResult] to request in view with name 'canvas'
DEBUG: org.springframework.web.servlet.view.JstlView - Added model object 'mcanvas' of type [com.journaldev.spring.model.GroupCanvas] to request in view with name 'canvas'
DEBUG: org.springframework.web.servlet.view.JstlView - Added model object 'org.springframework.validation.BindingResult.mcanvas' of type [org.springframework.validation.BeanPropertyBindingResult] to request in view with name 'canvas'
DEBUG: org.springframework.web.servlet.view.JstlView - Added model object 'listGroups' of type [java.util.ArrayList] to request in view with name 'canvas'
DEBUG: org.springframework.web.servlet.view.JstlView - Added model object 'username' of type [java.lang.String] to request in view with name 'canvas'
DEBUG: org.springframework.web.servlet.view.JstlView - Added model object 'firstname' of type [java.lang.String] to request in view with name 'canvas'
DEBUG: org.springframework.web.servlet.view.JstlView - Forwarding to resource [/WEB-INF/views/canvas.jsp] in InternalResourceView 'canvas'
DEBUG: org.springframework.web.servlet.DispatcherServlet - Successfully completed request

Incase someone needs the QT code, here it is :

LoginAndAccessSecuresResource :

 QString url_str = "http://localhost:8080/j_spring_security_check";
    QString canvasUrl = "http://localhost:8080/canvas/jsonlist";

QNetworkAccessManager *manager = new QNetworkAccessManager();
    manager->setCookieJar (new QNetworkCookieJar(manager));
    connect (manager,SIGNAL(finished(QNetworkReply*)),this,SLOT(slotRequestFinished(QNetworkReply*)));
    QNetworkRequest request;
    request.setUrl (url_str);
    request.setRawHeader("User-Agent", "MyOwnBrowser 1.0");
    QByteArray postData;
    postData.append ("j_username=email@email.de");
    postData.append ("&j_password=password");
    manager->post (request,postData);
    request.setUrl (canvasUrl);
    request.setRawHeader("User-Agent", "MyOwnBrowser 1.0");
    manager->get (request);

If there is any more information required, kindly let me know, more than happy to provide it. Thanks a lot. :-)

Get all elements of QListWidget

I have multiple instances of QListWidget on my UI. I would like to write all the elements of a specific QListWidget to a file.

How could I select every element of a specific QListWidget? (I already know how to write to a file...)

Internal QTimer isn't killed from the right thread when terminating a QThread

I have a QThread that creates a QGraphicsSimpleTextItem. When I close my application I try to finish the thread and then terminate it.

if( !QThread::wait(1000) )
    QThread::terminate();

Everything is fine until I add a call to QGraphicsSimpleTextItem::setFont() in my thread. If I do so, Qt's internal QFontCache system is called and will start a QTimer (from my thread). Then when I terminate the QThread, killTimer is called (from the main) when Qt cleans up the event loops and I get the error:

QObject::killTimers: timers cannot be stopped from another thread

What should I do to avoid this problem? Shouldn't that be considered as a bug of the font caching mechanism? Thanks for your help.

using boost whithin qt

I have installed qt-opensource-windows-x86-mingw491_opengl-5.4.1.exe and compile boost with mingw 4.9.1.
Now I want to link all boost libraries to my qt project likw what happened in visual studio.
any one can give a solution?