Multipart Configuration for JBoss Enterprise Application Platform/Application Server

Spring REST controller on Spring Boot (1.12) was not accepting multi-part requests for file upload on JBoss EAP/AS but working on Embedded Tomcat.

org.springframework.web.bind.MissingServletRequestParameterException: Required MultipartFile parameter 'file' is not present

I needed to add a multipart filter on my web xml configuration in Java

@Configuration
@ComponentScan
@EnableAutoConfiguration
@EnableJpaRepositories
@EnableSpringDataWebSupport
public class Application extends SpringBootServletInitializer {

 @Override
 protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
 return application.sources(Application.class);
 }

 @Override
 public void onStartup(ServletContext servletContext) throws ServletException {
 WebApplicationContext context = createRootApplicationContext(servletContext);
 ServletRegistration.Dynamic servletRegistration = servletContext.addServlet("dispatcher", new DispatcherServlet(context));
 servletRegistration.setLoadOnStartup(1);
 servletRegistration.addMapping("/*"); // required JBOSS EAP
 servletRegistration.setMultipartConfig(getMultiPartConfig()); // fixes multipart requests
 super.onStartup(servletContext);
 }

 private MultipartConfigElement getMultiPartConfig() {
 String location = "";
 long maxFileSize = -1;
 long maxRequestSize = -1;
 int fileSizeThreshold = 0;
 return new MultipartConfigElement(
 location,
 maxFileSize,
 maxRequestSize,
 fileSizeThreshold
 );
 }

 public static void main(String[] args) {
 SpringApplication.run(Application.class, args);
 }
}

My Spring and web.xml is configured via Java annotations.

I found this post for this configuration: http://stackoverflow.com/questions/19293862/how-make-the-setmultipartconfig-work-for-a-dynamic-added-servlet

Debugging Ruby Selenium Webdriver RSpec tests on JetBrains IntelliJ on a Java Project

So, you already have a Java project on IntelliJ and want to run and debug ruby selenium tests.

Specify Ruby SDK in IntelliJ for the project.
1. Navigate to File -> Project Structure -> SDKs -> Project.
2. Select SDK, in my case Ruby-2.0.0.
3. Click Apply and OK

Create a Ruby Module (This is specific to my scenario, so your module settings may be different)
1. Navigate to File -> Project Structure -> Modules
2. Remove existing Java module.
3. Create New Module based on Ruby Gem.
4. Select project’s root level as the module, rest of the fields autofill.
5. Remove Ruby Gem facet from module.
6. Click Apply and OK

Create RSpec Configuration
1. Edit Configuration -> Add New Configuration -> Rspec
2. Select spec and SDK.
3. Click Apply and OK
4. Run/debug

Troubleshooting
If you get the Teamcity Formatter error below error in Intellij when executing the RSpec script, try the following.
1. Execute the Create a Ruby Module step
2. Remove the existing RSpec configuration
3. Re-create the RSpec Configuration

/usr/bin/ruby -e $stdout.sync=true;$stderr.sync=true;load($0=ARGV.shift) /usr/bin/rspec spec.rb --require teamcity/spec/runner/formatter/teamcity/formatter --format Spec::Runner::Formatter::TeamcityFormatter
Testing started at 9:47 AM ...
/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/rubygems/core_ext/kernel_require.rb:55:in `require': cannot load such file -- teamcity/spec/runner/formatter/teamcity/formatter (LoadError)
from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/rubygems/core_ext/kernel_require.rb:55:in `require'
from /Library/Ruby/Gems/2.0.0/gems/rspec-core-2.14.8/lib/rspec/core/configuration.rb:867:in `block in setup_load_path_and_require'
from /Library/Ruby/Gems/2.0.0/gems/rspec-core-2.14.8/lib/rspec/core/configuration.rb:867:in `each'
from /Library/Ruby/Gems/2.0.0/gems/rspec-core-2.14.8/lib/rspec/core/configuration.rb:867:in `setup_load_path_and_require'
from /Library/Ruby/Gems/2.0.0/gems/rspec-core-2.14.8/lib/rspec/core/configuration_options.rb:25:in `configure'
from /Library/Ruby/Gems/2.0.0/gems/rspec-core-2.14.8/lib/rspec/core/command_line.rb:21:in `run'
from /Library/Ruby/Gems/2.0.0/gems/rspec-core-2.14.8/lib/rspec/core/runner.rb:80:in `run'
from /Library/Ruby/Gems/2.0.0/gems/rspec-core-2.14.8/lib/rspec/core/runner.rb:17:in `block in autorun'

Process finished with exit code 1

RESTful Web Services Popular Standards

My two favorite resources for REST standards.  I think they cover most use cases, and their suggestions are thought out and used in practice.  I recommend that both backend and frontend developers read/watch both!

  1. Storm Path
  2. Vinay Sahni

To see other links that I liked, check out my scoop.it page.

Apache Avro JSON Decoder for List/Array of Avro Objects

I couldn’t find a good example of decoding a JSON string that’s a list/array of Avro objects on the web. I just wanted to write a post to say that it works.

Here’s a few high level things that I remember

  • Create a JSON Decoder with Schema.createArray({avroObject}.getSchema())
  • When initializing the data reader, use List<{avroObject}> and also pass in an initialized instance of List<{avroObject}> along with the JSON Decoder created above.

It should work, but I had to use the debugger a few times to clear out some JSON issues.  I hope this helps – I spent a lot of unnecessary time checking whether something like this would work.  It looks like it’s supported out of the box.

Java Generics JSON Unmarshalling Using Jackson via Jersey Resource

Jackson seems to unmarshal properly for objects with a specific class type.  For types with generics, for example List<Element>, I could only specify the List.class, and the Element JSON was unmarshalled as LinkedHashMaps instead of the Element.class.

I found a way to work around it and applied it to the Jersey use case for my unit test.

ObjectMapper mapper = new ObjectMapper();
JavaType type = mapper.getTypeFactory().constructCollectionType(List.class, Element.class);

String json = client().resource("/some/collection").get(String.class);
List<Element> elements = mapper.readValue(json, type);

Sample Dropwizard Resource Test

I’m prototyping a dropwizard app, and it wasn’t clear in the docs how to write resource tests that handle authentication.  This example uses OAuth authentication.  I also found it annoying that there were no import statements in the documents.  Anyway, I hope this helps.  There are probably more efficient ways to do this, so I’ll update this post as I find out more.


package com.yourcompany.resource;

import static org.fest.assertions.api.Assertions.assertThat;
import static org.mockito.Matchers.anyObject;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import java.util.LinkedList;
import java.util.List;

import javax.ws.rs.core.MediaType;

import org.eclipse.jetty.server.Authentication.User;
import org.junit.Before;
import org.junit.Test;

import com.yourcompany.dao.SampleDao;
import com.yourcompany.dto.SampleItem;
import com.yourcompany.dto.Sample;
import com.yourcompany.oauth.OAuthAuthenticator;
import com.sun.jersey.api.client.ClientHandlerException;
import com.sun.jersey.api.client.ClientRequest;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.filter.ClientFilter;
import com.yammer.dropwizard.auth.oauth.OAuthProvider;
import com.yammer.dropwizard.testing.ResourceTest;

public class SampleResourceTest extends ResourceTest {
 private final Sample sample = new Sample();
 private final SampleDao dao = mock(SampleDao.class);

@Override
 protected void setUpResources() {
 List<SampleItem> sampleItems = new LinkedList<SampleItem>();

 sample.setSampleItems(sampleItems);

 when(dao.fetchSample(anyString())).thenReturn(sample);
 when(dao.postSample((Sample)anyObject())).thenReturn(sample);
 addResource(new SampleResource(dao));
 addProvider(new OAuthProvider<User>(new OAuthAuthenticator(), "CLIENT_SECRET"));
 }

 @Before
 public void testBefore() {
 client().addFilter(new ClientFilter() {
 private List<Object> authorizations;

@Override
 public ClientResponse handle(ClientRequest request) throws ClientHandlerException {
 if (authorizations == null) {
 authorizations = new LinkedList<Object>();
 authorizations.add("Bearer {test token}");
 }
 request.getHeaders().put("Authorization", authorizations);
 ClientResponse response = getNext().handle(request);

 return response;
 }
 });
 }

 @Test
 public void testFetchSample() throws Exception {
 Sample retrievedSample = client().resource(String.format("/sample-service/sample/id/", "id")).get(Sample.class);
 compareSample(retrievedSample);
 verify(dao).fetchSample(anyString());
 }

 @Test
 public void testPostSample() throws Exception {
 Sample retrievedSample = client().resource("/sample-service/sample").type(MediaType.APPLICATION_JSON_TYPE).post(Favorites.class, favorites);
 compareSample(retrievedSample);
 verify(dao).postSample((Sample)anyObject());
 }

 private void compareSample(Sample retrievedSample) {
 assertThat(retrievedSample.getWhatever()).isEqualTo(sample.getWhatever());
 // other assertions
 }
}

** EDIT
I created a TestOAuthAuthenticator that I pass into my test as a provider. This authenticator has pre-defined tokens and users for tests.

Loading Resources from an Imported JAR

The ClassLoader can be used to reference a resource in a JAR.  For example, if I packaged a JAR with a file called file.xml in the directory path/in/JAR, I would use the code below.

this.getClass().getClassLoader().getResource(“path/in/JAR/file.xml”);

If you need to reference other files, it may be smart to use a Java Enum to store these locations for better organization.