Exception error in google doc api - api

I am new to google api. I am trying to create a simple web application (Java EE) to read DocumentListFeed from google doc. My code in the servlet is:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
try
{
DocsService service = new DocsService("Document List Demo");
service.setUserCredentials(NAME, PASSWORD);
response.getWriter().println("helloooooo");
//URL documentListFeedUrl = new URL("http://docs.google.com/feeds/documents/private/full");
URL documentListFeedUrl = new URL("https://docs.google.com/feeds/default/private/full?v=3");
DocumentListFeed feed = service.getFeed(documentListFeedUrl, DocumentListFeed.class);
for(DocumentListEntry entry : feed.getEntries())
{
response.getWriter().println(entry.getTitle().getPlainText());
}
}
catch (Exception e)
{
response.getWriter().println(e);
}
}
But it is showing me the error: java.lang.NoClassDefFoundError: com/google/gdata/client/docs/DocsService
I am using Glassfish server and Ecllipse. And added external jar file: activation.jar, guava-r07.jar, mail.jar, servlet.jar, gdata-client-1.0.jar, gdata-client-meta-1.0.jar, gdata-core-1.0.jar, gdata-media-1.0.jar, gdata-docs-3.0.jar, gdata-docs-meta-3.0.jar.
I have copied this same code to java standard edition and it is working fine. Could please tell me why this thing is not working in Java EE? Is it a problem in GlassFish server?

It just means that the jars are not present in your Glassfish server classpath.
Add all the jars you listed to yuor glassfish server classpath. Since am not an Glassfish expert i cannot help you in adding the jars to your server.
In case of weblogic, you just need to package all the jars in your project APP-INF directory.
Hope it helps.

Related

url was not normalized error when using intellij but not when using STS

The developed website works fine on remote server and local machine (when using STS IDE) , recently I started use Intellij IDEA (I created a duplicate of the website code with no any changes ), I started getting the URL was not normalized error.
Does intellij handles Spring security somehow differently than STS ? or what could be the cause?
I don't want use custom httpfirewal .
#EnableGlobalMethodSecurity(prePostEnabled=true)
#Configuration
#EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter{
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authenticationProvider())
.jdbcAuthentication()
.usersByUsernameQuery(usersQuery)
.authoritiesByUsernameQuery(rolesQuery)
.dataSource(dataSource);
}
#Override
protected void configure(HttpSecurity http) throws Exception {
// URLs matching for access rights
http.authorizeRequests()
.antMatchers( "/", "/contact","/register").permitAll()
.antMatchers("/accounts").hasAnyAuthority("SUPER_USER","ADMIN_USER")
.anyRequest().authenticated()
.and()
// form login
.csrf().disable().formLogin()
.loginPage("/index")
.failureUrl("/index?error=true")
.defaultSuccessUrl("/user")
.usernameParameter("email")
.passwordParameter("password")
.and()
// logout
.logout()
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/").and()
.exceptionHandling()
.accessDeniedPage("/access-denied");
}
#Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/resources/**", "/static/**", "/css/**", "/js/**", "/images/**");
}
and this is from the properties :
# Spring MVC view prefix.
spring.mvc.view.prefix=/templates/
# Spring MVC view suffix.
spring.mvc.view.suffix=.html
the error is :
org.springframework.security.web.firewall.RequestRejectedException: The request was rejected because the URL was not normalized.
P.S: I'm using JDK8 ,Spring Boot 2,Spring Security ,thymeleaf,intellij U 2019.2
org.springframework.security.web.firewall.RequestRejectedException: The request was rejected because the URL was not normalized.
Which IDE to use should not have any differences for running the same source codes on the embeddable server configured by springboot. This error happens when the HTTP requests that send to server is not normalised which the URL contains character sequences like ./, /../ , // or /. So I doubt that it is due to you are using different URL to browse the app. For example, you are accidentally adding a '/' in the URL such as http://127.0.0.1:8080/app//index.html
You can change to use a less secure HttpFirewall to avoid such checking by :
#Override
public void configure(WebSecurity web) throws Exception {
web.httpFirewall(new DefaultHttpFirewall());
//another configuration .....
}
P.S. Though it is called DefaultHttpFirewall , it is not the default HttpFirewall used by Spring Security since 4.2.4 which is less secured than the actual default StrictHttpFirewall

TomEE Embedded: Resource defined in resources.xml not available within webapp

I'm currently trying to run a simple webapp on TomEE Embedded (TomEE Version 7.0.5).
According to the docs, I can start the TomEE and deploy the classpath as a webapp like this. I've set the document base to src/main/webapp.
try (final Container container = new Container(new Configuration())
.deployClasspathAsWebApp("", new File("src/main/webapp"))) {
container.await();
}
I have defined a datasource in WEB-INF/resources.xml which looks like this:
<Resource id="myDataSource" type="javax.sql.DataSource">
JdbcDriver org.hsqldb.jdbcDriver
JdbcUrl jdbc:hsqldb:file:hsqldb
UserName sa
Password
</Resource>
And I've setup a reference in the web.xml:
<resource-ref>
<res-ref-name>myDataSource</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
</resource-ref>
Then I try to lookup this datasource in my Servlet via JNDI.
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
try {
Context initCtx = new InitialContext();
DataSource ds = (DataSource) initCtx.lookup("java:comp/env/myDataSource");
Connection connection = ds.getConnection();
...
}
When the TomEE starts, it seems like my DataSource is created (at least there is some output about that in the logs). However when I try to lookup the DataSource in my servlet, I get an unconfigured dbcp2 connection pool as a DataSource which throws the following exception when ds.getConnection() is called:
java.sql.SQLException: Cannot create JDBC driver of class '' for connect URL 'null'
at org.apache.tomcat.dbcp.dbcp2.BasicDataSource.createConnectionFactory(BasicDataSource.java:2186)
at org.apache.tomcat.dbcp.dbcp2.BasicDataSource.createDataSource(BasicDataSource.java:2066)
at org.apache.tomcat.dbcp.dbcp2.BasicDataSource.getConnection(BasicDataSource.java:1525)
at TestServlet.doGet(TestServlet.java:32)
...
The same configuration works fine on a standalone TomEE (I tried TomEE Webprofile) or when using the TomEE Maven Plugin. Is there anything I'm missing to get it running also for Embedded TomEE?
Thanks in advance
Tomee embedded does not bind a custom webapp classloader by default so does not have comp/ always bound. You can pass properties to the context to force it to be openejb one or use openejb:Resource/myDataSource or java:openejb/Resource/myDataSource naming.

custom login module to access httpservletrequest in JBOSS EAP

I am developing a custom login module for jboss' jaas implementation. I would like to be able to access the HttpServletRequest object inside my login module. Does anyone know the best way to do this, if it's possible? I've been researching this, and so far I think I need to use a Callback of some kind, but I'm not sure.I found some WebSphere documentation that shows they have a WSServletRequestCallback that seems to be able to do this. Please suggest a simple example or documentation if jboss' jaas implementation have anything like this.
Update:
#kwart: As per your suggestion, I coded the following. Please suggest if this is the right way:
protected CallbackHandler _callbackHandler;
HttpServletRequest request = null;
ObjectCallback objectCallback = null;
Callback[] callbacks = new Callback[1];
callbacks[0] = objectCallback = new ObjectCallback("HttpServletRequest: ");
try
{
_callbackHandler.handle(callbacks);
}
catch (Exception e)
{
logger.logp(Level.SEVERE, CLASSNAME, METHOD_NAME, "Error handling callbacks", e);
}
try
{
if (objectCallback != null)
{
request = (HttpServletRequest) PolicyContext.getContext("javax.servlet.http.HttpServletRequest");
}
}
catch (PolicyContextException e) {
logger.logp(Level.SEVERE, CLASSNAME, METHOD_NAME, "Error getting request", e);
}
catch (Exception e)
{
logger.logp(Level.SEVERE, CLASSNAME, METHOD_NAME, "Exception occured augmenting JbossSubject", e);
}
You can use JACC PolicyContext to retrieve the HttpRequestObject in the LoginModule methods:
HttpServletRequest request = (HttpServletRequest) javax.security.jacc.PolicyContext
.getContext(HttpServletRequest.class.getName());
Update: Find sample usage in LoginModule here.
I got a solution from this site.
Used JSPI authentication. Configured an auth module in security domain in standalone as explained here .
Created a custom authenticator and a custom login module, configured the authenticator in jboss-web.xml and login module in security domain in standalone xml.
I jar'd them in a separate module and added that to jboss-deployment-structure.xml. Stored http request in ThreadLocal in the authenticator and retrieved it in my login module by simply reading the value stored in the Thread Local.

Create a servlet-filter websphere liberty profile?

I'm working with an websphere liberty profile webserver where i have deployed a couple of applications.
These applications are sending request message's, I want to create a servlet-filter without changing the applications
so i can see what the application is sending and receiving. Also i want to add new request headers.
You can use a ServletContainerInitializer to register new ServletFilters. An example implementation that adds a response header might look like this:
public class SCI implements ServletContainerInitializer {
#Override
public void onStartup(Set<Class<?>> arg0, ServletContext arg1)
throws ServletException {
arg1.addFilter("myFilter", MyFilter.class).addMappingForUrlPatterns(null, false, "/*");
}
}
The MyFilter class would look like this:
public static class MyFilter implements Filter {
#Override
public void destroy() { }
#Override
public void doFilter(ServletRequest arg0, ServletResponse arg1,
FilterChain arg2) throws IOException, ServletException {
if (arg1 instanceof HttpServletResponse) {
((HttpServletResponse) arg1).addHeader("Test", "Test");
}
arg2.doFilter(arg0, arg1);
}
#Override
public void init(FilterConfig arg0) throws ServletException { }
}
You then need to register this using a file in called META-INF/services/ServletContainerInitializer which should contain the fully qualified class name of the Servlet Container Initializer, for example:
test.SCI
Normally you package these in a jar in the application, but since you don't want to update the application you instead configure the server like this:
<featureManager>
<feature>bells-1.0</feature>
</featureManager>
<library id="init">
<file name="path/to/jar"/>
</library>
<bell libraryRef="init"/>
The ServletContainerInitializer will be called for all started Web applications allowing you to add the filter. Note this will be called for all started Web applications including ones integrated into the Liberty runtime, such as the Admin Center and the REST connector.
I got the below response when I tried to install the same bells utility
CWWKF1295E: The bells-1.0 asset cannot be downloaded or installed to IBM WebSphere Application Server Liberty (ILAN) 19.0.0.4 because it applies only to the following product editions and versions:
IBM WebSphere Application Server Liberty 8.5.5.7
IBM WebSphere Application Server Liberty for Developers 8.5.5.7
IBM WebSphere Application Server Liberty - Express 8.5.5.7
IBM WebSphere Application Server Liberty Liberty Core 8.5.5.7
IBM WebSphere Application Server Liberty Network Deployment 8.5.5.7
IBM WebSphere Application Server Liberty z/OS 8.5.5.7
Use the installUtility find action to retrieve a list of assets that apply to your installation.

Could not load middleware layer 'com.sap.mw.jco.rfc.MiddlewareRFC'

I'm using Sap Jco to connect to SAP database with the front end being Java(JSF), When I connect to SAP with:
try {
mConnection =JCO.createClient("400", // SAP client
"c3026902", // userid
"********", // password
"EN", // language
"iwdf5020", // host name
"00"); // system number
mConnection.connect();
}
catch (Exception ex) {
ex.printStackTrace();
System.exit(1);
}
Problem I'm facing is when run the application for the first time, data is displayed but when I re-run it says "Could not load middleware layer 'com.sap.mw.jco.rfc.MiddlewareRFC' "
Can any one help me in resolving the issue?????
This sounds like the API cannot load the native driver files.
The SAP Java Connector consists of a native runtime part, that does the actuall communication and a Java API that wraps this functionality with a java api.
The Java API is inside the sapjco.jar and the native drivers are e.g on windows inside librfc32.dll and sapjcorfc.dll.
Place these dll's into your system path (e.g. windows: C:\WiNDOWS\system32) and it should run.
Cheers
Sebastian
Are your DLLs located in the Windows system32 folder? If so, are you probably using the wrong architecture? (x64 DLL on 32 bit or vice versa)
Also, are the DLLs the same version as the java api? If you have SAP GUI installed there could be older DLLs around.
Defining SAP connection:
For the Version 3,0 of the sapjco library there exists plenty of useful information. To create a connection following the instructions in:
http://www.browseye.com/linkShare.html?url=http://help.sap.com/saphelp_nwpi711/helpdata/en/46/fb807cc7b46c30e10000000a1553f7/content.htm?bwsCriterion=%22Setting%20Up%20Connection%22&bwsMatch=1&bwsCriterion=%22Setting%20Up%20Connection%22&bwsMatch=1
There are a few thing that you should take into account:
Place the dll file in the same place that the jar.
The dll must be the right version for your operating system and architecture otherwise you will get a native library error.
Example of code to create a connection to the server.
public class StepByStepClient
{
static String DESTINATION_NAME1 = "ABAP_AS_WITHOUT_POOL";
static String DESTINATION_NAME2 = "ABAP_AS_WITH_POOL";
static
{
Properties connectProperties = new Properties();
connectProperties.setProperty(DestinationDataProvider.JCO_ASHOST, "ls4065");
connectProperties.setProperty(DestinationDataProvider.JCO_SYSNR, "85");
connectProperties.setProperty(DestinationDataProvider.JCO_CLIENT, "800");
connectProperties.setProperty(DestinationDataProvider.JCO_USER, "homofarber");
connectProperties.setProperty(DestinationDataProvider.JCO_PASSWD, "laska");
connectProperties.setProperty(DestinationDataProvider.JCO_LANG, "en");
createDestinationDataFile(DESTINATION_NAME1, connectProperties);
connectProperties.setProperty(DestinationDataProvider.JCO_POOL_CAPACITY, "3");
connectProperties.setProperty(DestinationDataProvider.JCO_PEAK_LIMIT, "10");
createDestinationDataFile(DESTINATION_NAME2, connectProperties);
}
static void createDestinationDataFile(String destinationName, Properties connectProperties)
{
File destCfg = new File(destinationName+".jcoDestination");
try
{
FileOutputStream fos = new FileOutputStream(destCfg, false);
connectProperties.store(fos, "for tests only !");
fos.close();
}
catch (Exception e)
{
throw new RuntimeException("Unable to create the destination files", e);
}
}
public static void step1Connect() throws JCoException
{
JCoDestination destination = JCoDestinationManager.getDestination(DESTINATION_NAME1);
System.out.println("Attributes:");
System.out.println(destination.getAttributes());
System.out.println();
}
}
In SAPJco 3.0 connections are build from the info contained in a “Destination”.
The documentation example use a properties file to save the “Destination”. However it is a non-secure way to keep connection info. As is indicated on the documentation in the hightlighted paragraph you can see on next link.
http://help.sap.com/saphelp_nwpi711/helpdata/en/48/5fb9f9b523501ee10000000a421937/content.htm?bwsCriterion=%22In%20practice%20you%20should%20avoid%20this%20for%20security%20reasons.%22&bwsMatch=1
You can keep connection info on a database or any other storage system if you create a custom “DestinationDataProvider” In the Examples provided with the SAPJco library there is an example of how to create a custom DestinationDataProvider.